简体   繁体   中英

JSON.NET: Serialize json string property into json object

Is it possible to tell JSON.NET I have a string with JSON data? Eg I have a class like this:

public class Foo
{
    public int Id;
    public string RawData;
}

which I use like this:

var foo = new Foo();
foo.Id = 5;
foo.RawData = @"{""bar"":42}";

which I want to be serialized like this:

{"Id":5,"RawData":{"bar":42}}

Basically I have a piece of unstructured variable-length data stored as JSON already, I need fully serialized object to contain this data as a part.

Thanks.

EDIT: Just to make sure it is understood properly, this is one-way serialization, ie I don't need it to deserialize back into same object; the other system shall process this output. I need content of RawData to be a part of JSON, not a mere string.

You need a converter to do that, here is an example:

public class RawJsonConverter : JsonConverter
{
   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
       writer.WriteRawValue(value.ToString());
   }

   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
       throw new NotImplementedException();
   }

   public override bool CanConvert(Type objectType)
   {
       return typeof(string).IsAssignableFrom(objectType);
   }

   public override bool CanRead
   {
       get { return false; }
   }   
}

Then decorate your class with it:

public class Foo
{
    public int Id;
    [JsonConverter(typeof(RawJsonConverter))]
    public string RawData;
}

Then, when you use:

var json = JsonConvert.SerializeObject(foo,
                                    new JsonSerializerSettings());
Console.WriteLine (json);

This is your output:

{"Id":5,"RawData":{"bar":42}}

Hope it helps

Edit: I have updated my answer for a more efficient solution, the previous one forced you to serialize to then deserialize, this doesn't.

It is possible, that using JRaw could be more sutable and comapct solution

see this post

You can use another property to deserialize the object property json.

public class Foo
{
    public int Id;
    public string RawData;
    private object thisObject;
    public object ThisObject 
    {
        get
        {
            return thisObject ?? (thisObject = JsonConvert.DeserializeObject<object>(RawData));
        }
    }        
}

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