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

c# - Serialize an object's properties to separate JSON objects in an array

I want to serialize properties but with each property enclosed in a separate JSON object in an array.

Example below:

public class Metadata
{
    public string Name { get; set; }
    public Guid Id { get; set; }
}

public void SerializeCars()
{
    var data = new Metadata { Name = "MyName", Id = Guid.NewGuid() };
    var json = JsonConvert.SerializeObject(data, Formatting.Indented);
}

Current result will be:

{
    "Name": "MyName",
    "Id": "f9c4bc06-0b99-47ff-b22b-ea094fc188ee"
}

I want it to be (missing "td" class above):

{
    "td": [{
        "name": "myName"
    }, {
        "id": "f9c4bc06-0b99-47ff-b22b-ea094fc188ee"
    }]
}

Can it be fixed?

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 a custom JsonConverter to get the output you want:

class MetadataConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Metadata));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JArray array = new JArray();
        foreach (PropertyInfo pi in value.GetType().GetProperties().Where(p => p.CanRead))
        {
            array.Add(new JObject(new JProperty(pi.Name, pi.GetValue(value, null))));
        }
        JObject obj = new JObject(new JProperty("td", array));
        obj.WriteTo(writer);
    }

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

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

}

Then, use it like this:

var json = JsonConvert.SerializeObject(data, Formatting.Indented, new MetadataConverter());

Fiddle: https://dotnetfiddle.net/5IRDeu


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

1.4m articles

1.4m replys

5 comments

57.0k users

...