简体   繁体   中英

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

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.

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

It's as simple as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM