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

穿精又带淫゛_ 提交于 2019-12-24 17:53:24

问题


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?


回答1:


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




回答2:


If you need it to serialize that way, try some post-processing on the serialized string. Keep in mind this won't deserialize well without some processing before deserialization.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft;
using Newtonsoft.Json.Linq;

namespace ConsoleApplication1
{

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

    public class Root
    {
        public List<Metadata> listOfMetadata{get;set;}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Run run = new Run();
            run.SerializeCars();
        }
    }

    public class Run
    {
        public void SerializeCars()
        {
            var root = new Root()
            {
                listOfMetadata = new List<Metadata>()
                {
                    new Metadata
                    { 
                        Name = "MyName", Id = Guid.NewGuid()
                    }
                }
            };

            var json = JsonConvert.SerializeObject(root, Formatting.Indented);
            json = json.Replace("\"listOfMetadata\": ", string.Empty);
            Console.WriteLine(json);
            Console.ReadKey();
        }
    }
}


来源:https://stackoverflow.com/questions/36201875/serialize-an-objects-properties-to-separate-json-objects-in-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!