我有以下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.
推荐答案在获得其他答案的帮助并看了一些文档之后,我发现了 JObject.Load 方法.我的转换器现在可以工作了,看起来像这样:
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字符串?
发布评论