这是我非常简单的C#类对象,我试图将其变成一个JSON字符串并弦字节:
: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 String
public static string Stringify(string json)
{
return JsonConvert.ToString(json);
}
生成以下(我认为这是预期的?)输出的输出:
"{"Name":"Hello","State":7}"
我的问题如何从:
"{"Name":"Hello","State":7}"
回到rtestObject?
这是我尝试过的:
尝试1
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."}
解决方案:
谢谢Alexander I.!
public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
{
var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
return ConvertFromJSON<T>(json);
}
请查看下一个示例:
class Program
{
static void Main(string[] args)
{
var test = new TestObject
{
Name = "Hello",
State = 7
};
var json = ConvertToJson(test);
var stringify = Stringify(json);
var result = StringifyToObject<TestObject>(stringify);
}
public static string ConvertToJson<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
public static string Stringify(string json)
{
return JsonConvert.ToString(json);
}
public static T StringifyToObject<T>(string stringify)
{
var json = JsonConvert.DeserializeObject<string>(stringify);
var result = JsonConvert.DeserializeObject<T>(json);
return result;
}
}
public class TestObject
{
public TestObject()
{
Name = "Hi";
State = 0;
}
public string Name { get; set; }
public int State { get; set; }
}
查看StringifyToObject
方法。
- 将字符串字符串转换为JSON String
- deasirialize json字符串到对象
喜欢 @ne1410写作,使用: JsonConvert.DeserializeObject<rTestObject>(myJsonString);
您不必串起JSON,它已经是一个字符串,如JsonConvert.SerializeObject(obj)
您不需要任何其他方法IMO。