【发布时间】:2018-05-20 20:21:22
【问题描述】:
这是我尝试将其转换为 JSON 字符串并进行字符串化的非常简单的 C# 类对象:
public class rTestObject
{
public rTestObject()
{
Name = "Hello";
State = 7;
}
public string Name { get; set; }
public int State { get; set; }
}
我调用下面的静态方法:
// Json.net
// from Newtonsoft.Json.dll
// version 8.0.2.19309
//
using Newtonsoft.Json;
public static string ConvertToJSON<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
产生以下(预期的)输出:
{"Name":"Hello","State":7}
我调用以下静态方法对我的 JSON 字符串进行字符串化
public static string Stringify(string json)
{
return JsonConvert.ToString(json);
}
产生以下(我认为这是预期的??)输出:
"{\"Name\":\"Hello\",\"State\":7}"
我的问题是如何得到的:
"{\"Name\":\"Hello\",\"State\":7}"
返回 rTestObject?
这是我尝试过的:
试一试
public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
{
Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
return ConvertFromJSON<T>(j.ToString());
}
这是一个例外:
{"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}
尝试 2
public static T ConvertFromJSON<T>(string jsonNotation)
{
return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
}
这是一个例外:
{"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}
解决方案:
谢谢亚历山大一世!
public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
{
var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
return ConvertFromJSON<T>(json);
}
【问题讨论】:
-
你试过
JsonConvert.DeserializeObject<type>(str); -
尝试使用 Jason 属性进行装饰 stackoverflow.com/a/8796648/1585883 newtonsoft.com/json/help/html/… 或使用 Datacontracts 得到你想要的 msdn.microsoft.com/en-us/library/jj870778.aspx
-
我认为我不需要添加“Jason 属性”或“Datacontracts”......我相信这应该是一个非常简单的操作......但只是不知道 Json。 net api 足以编写代码...
标签: c# json json.net stringify