jas*_*son 3 c# serialization json json.net deserialization
我正在采取我的第一次认真尝试与Json合作并将其从一个应用程序返回到另一个应用程序.
我的应用程序是使用.Net 4.0 Framework的ASP.NET MVC 3应用程序.
我需要将一个非常简单的类序列化和反序列化为json.
public class ProxyRequestResultDetails
{
public string ApplicationName { get; set; }
public string ProxyValue { get; set; }
public bool ProxyRelationshipExists { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该类不继承或实现任何东西.
我可以通过执行以下操作将其成功转换为json:
string json = JsonConvert.SerializeObject(requestDetails);
Run Code Online (Sandbox Code Playgroud)
创建的json的一个示例是:
"{\"ApplicationName\":\"Awesome App\",\"ProxyValue\":\"0\",\"ProxyRelationshipExists\":true}"
Run Code Online (Sandbox Code Playgroud)
然后我拨打以下电话:
ProxyRequestResultDetails deserializedTestRequestDetails =
JsonConvert.DeserializeObject<ProxyRequestResultDetails>(json);
Run Code Online (Sandbox Code Playgroud)
这有一个如下所示的堆栈跟踪.它被格式化为包含所有内部异常的赌注.
Method: CustomHandleErrorAttribute
Message: Error converting value "{\"ApplicationName\":\"Awesome App\",\"ProxyValue\":\"0\",\"ProxyRelationshipExists\":true}" to type 'ProxySetup.Models.ProxyRequestResultDetails'. Path '', line 1, position 98. Inner Error #1: Could not cast or convert from System.String to ProxySetup.Models.ProxyRequestResultDetails.
stack trace: at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常简单的对象.我可能遗漏了一些简单的东西,但我无法从例子中找到确切的东西.任何想法将不胜感激.
编辑1
严肃是对的.这正是发生的事情,但我不确定如何适应它.我正在尝试做的是在控制器上公开一个动作,以便它可以像Web服务调用一样使用.在操作中作为原始字符串创建的json是:
{"ApplicationName":"Awesome App","ProxyValue":"0","ProxyRelationshipExists":true}
Run Code Online (Sandbox Code Playgroud)
但是动作返回的json(返回类型为JsonResult)
return Json(json, "application/json; charset=utf-8", JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
是:
"{\"ApplicationName\":\"Awesome App\",\"ProxyValue\":\"0\",\"ProxyRelationshipExists\":true}"
Run Code Online (Sandbox Code Playgroud)
思考?
编辑2 - 已解决
这很简单.我将动作返回类型更改为
string
Run Code Online (Sandbox Code Playgroud)
并从以下位置返回结果字符串:
string json = JsonConvert.SerializeObject(requestDetails);
Run Code Online (Sandbox Code Playgroud)
呼叫.
谢谢你!
看起来您的序列化字符串已被转义或类似的东西,使其显示为表示字符串的字符串,而不是表示JSON流的字符串.
举个例子 :
string json = "{}";
string notJson = "\"{}\"";
Run Code Online (Sandbox Code Playgroud)
因此,请使用VS调试器检查字符串的原始值.
| 归档时间: |
|
| 查看次数: |
7361 次 |
| 最近记录: |