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
456 views
in Technique[技术] by (71.8m points)

c# - Merge two objects during serialization using json.net?

I met a situation as below could anybody help me achieve as below?

For Example, if I have the class:-

public class Sample
{
    public String name {get;set;}
    public MyClass myclass {get;set;}
}

My Myclass will be as follow:

public class MyClass
{
    public String p1 {get;set;}
    public String p2 {get;set;}
}

When I am using Json.net to Serialize the object of the class Sample,I got as below and it works well.

{
 "name":"...",
 "myclass":
          {
            "p1":"...",
            "p2":"..."
           }
 }

Its correct but I wonder is it possible to get the json string as below?

{
 "name":"...",
 "p1":"...",
 "p2":"..."
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can create anonymous object and serialize it:

var sample = new Sample { 
    name = "Bob", 
    myclass = new MyClass { 
                p1 = "x", 
                p2 = "y" 
              }};

string json = JsonConvert.SerializeObject(new { 
                 sample.name, 
                 sample.myclass.p1, 
                 sample.myclass.p2 
              });

Result

{"name":"Bob","p1":"x","p2":"y"}

But I suggest you either use default serialization of your Sample class, or create class which will be serialized into your format (i.e. move MyClass properties into Sample).

UPDATE: You can use custom converter, which flattens object and serializes all inner objects properties as top level object properties:

public class FlattenJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, 
        JsonSerializer serializer)
    {
        JToken t = JToken.FromObject(value);
        if (t.Type != JTokenType.Object)
        {
            t.WriteTo(writer);
            return;
        }

        JObject o = (JObject)t;
        writer.WriteStartObject();
        WriteJson(writer, o);
        writer.WriteEndObject();
    }

    private void WriteJson(JsonWriter writer, JObject value)
    {
        foreach (var p in value.Properties())
        {
            if (p.Value is JObject)
                WriteJson(writer, (JObject)p.Value);
            else
                p.WriteTo(writer);
        }
    }

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

    public override bool CanConvert(Type objectType)
    {
        return true; // works for any type
    }
}

Usage:

string json = JsonConvert.SerializeObject(sample, new FlattenJsonConverter());

Or you can simply hide anonymous type creation into custom converter, if you need this behavior for one type only:

public class SampleJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, 
        object value, JsonSerializer serializer)
    {
        Sample sample = (Sample)value;
        JToken t = JToken.FromObject(new { 
                      sample.name, 
                      sample.myclass.p1, 
                      sample.myclass.p2 
                   });

        t.WriteTo(writer);
    }

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

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Sample);
    }
}

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

...