如何将json对象反序列化为json字符串?

编程入门 行业动态 更新时间:2024-10-27 19:25:57
本文介绍了如何将json对象反序列化为json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下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字符串?

本文发布于:2023-11-17 07:44:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609344.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   序列   如何将   对象   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!