如何将json对象反序列化为json字符串? [英] How can I deserialize a json object into a json string?
问题描述
我有以下json:
{
"name" : "tim",
"items" : {
"car" : "Mercedes",
"house" : "2 Bedroom"
}
}
要反序列化为的对象是:
The object to deserialize into is:
public class Person
{
public string Name {get;set;}
public string Items {get;set;}
}
我想将items
反序列化为json对象的字符串.因此,本例中的Items
应该是
I want to deserialize items
into a string of the json object. So Items
in this example should be
"{\"car\" : \"Mercedes\",\"house\" : \"2 Bedroom\"}"
我不在乎空格,例如制表符或换行符.如何使用Newtonsoft.Json
做到这一点?我已尝试制作JsonConverter<string>
,如此处所示,但reader.Value
出现为null
.
I don't care about spacing such as tabs or new lines. How can I do this using Newtonsoft.Json
? I've tried making a JsonConverter<string>
as shown here but reader.Value
comes up as null
.
我想避免反序列化items
,然后再次将其序列化为字符串,因为我不知道items
的形状,而且它可能也很大. >
I would like to avoid deserializing items
and then serializing it into a string again as I do not know what shape items
will be and it may also be large.
推荐答案
After some help from the other answers here and looking at the docs some more, I discovered the JObject.Load
method. My converter works now, and looks like this:
public class StringConverter : JsonConverter<String>
{
public override void WriteJson(JsonWriter writer, String value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return JObject.Load(reader).ToString();
}
}
现在我可以使用如下属性:
And I can now use the attribute like this:
public class Person
{
public string Name {get;set;}
[JsonConverter(typeof(StringConverter))]
public string Items {get;set;}
}
这篇关于如何将json对象反序列化为json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!