Kurren
Kurren

Reputation: 837

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.

Upvotes: 0

Views: 175

Answers (2)

Kurren
Kurren

Reputation: 837

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

Upvotes: 2

Ali Bdeir
Ali Bdeir

Reputation: 4375

It's as simple as:

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

Upvotes: 0

Related Questions