Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c# - JSON.NET: Serialize json string property into json object

Is it possible to tell JSON.NET I have a string with JSON data? E.g. 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, i.e. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...