How can I deserialize a json object into a json string?

不问归期 提交于 2021-01-29 16:20:00

问题


I have the following 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;}
}

I want to deserialize items into a string of the json object. So Items in this example should be

"{\"car\" : \"Mercedes\",\"house\" : \"2 Bedroom\"}"

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.

Edit: 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.


回答1:


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;}
}



回答2:


It's as simple as:

var person = JsonConvert.DeserializeObject<Person>(json);
string itemsJson = JsonConvert.SerializeObject(person.Items);


来源:https://stackoverflow.com/questions/61138752/how-can-i-deserialize-a-json-object-into-a-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!