开发者

How to convert a List<T> to specific Json format

I want to be able to convert a List<T> into a specific JSON table-like format. In my case, the T will always be a simple object (no nested properties). Here are two examples to illustrate what I want.

Example #1: List<Person> to JSON

// C# list of Persons
var list = new List<Person>() {
  new Person() { First = "Jesse", Last = "Gavin", Twitter = "jessegavin" },
  new Person() { First = "John", Last = "Sheehan", Twitter = "johnsheehan" }
};

// I want to transform the list above into a JSON object like so
{
  columns : ["First", "Last", "Twitter"],
  rows: [
    ["Jesse", "Gavin", "jessegavin"],
    ["John", "Sheehan", "johnsheehan"]
  ]
}

Example #2: List<Address> to JSON

// C# list of Locations
var list = new List<Location>() {
  new Location() { City = "Los Angeles", State = "CA", Zip = "90210" },
  new Location() { City = "Saint Paul", State = "MN", Zip = "55101" },
};

// I want to transform the list above into a JSON object like so
{
  columns : ["City", "State", "Zip"],
  rows: [
    ["Los Angeles", "CA", "90210"],
    ["Saint Paul", "MN", "55101"]
  ]
}

Is there a way to tell JSON.net to serialize an object in this manner? If not, how could I accomplis开发者_Python百科h this? Thanks.

UPDATE:

Thanks to @Hightechrider's answer, I was able to write some code that solves the problem.

You can view a working example here https://gist.github.com/1153155


Using reflection you can get a list of properties for the type:

        var props = typeof(Person).GetProperties();

Given an instance of a Person p you can get an enumeration of the property values thus:

        props.Select(prop => prop.GetValue(p, null))

Wrap those up in a generic method, add your favorite Json serialization and you have the format you want.


Assuming your using .Net 4 this should do everything you want. The class actually lets you convert to either XML or JSON. The Enum for CommunicationType is at the bottom. The serializer works best if the class your passing it has been decorated with DataContract & DataMember attributes. I've included a sample at the bottom. It will also take an anonymous type so long as it's all simple types.

Reflection would work as well but then you have to understand all the JSON nuances to output complex data types, etc. This used the built-in JSON serializer in .Net 4. One more note, because JSON does not define a date type .Net puts dates in a funky ASP.Net custom format. So long as your deserializing using the built-in deserializer it works just fine. I can dig up the documentation on that if you need.

using System;
using System.Xml.Serialization;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml.Linq;

internal class Converter
{

    public static string Convert<T>(T obj, CommunicationType format, bool indent = false, bool includetype = false)
    {
        if (format == CommunicationType.XML)
        {
            return ToXML<T>(obj, includetype, indent);
        }
        else if (format == CommunicationType.JSON)
        {
            return ToJSON<T>(obj);
        }
        else
        {
            return string.Empty;
        }

    }

    private static string ToXML<T>(T obj, bool includetype, bool indent = false)
    {
        if (includetype)
        {
            XElement xml = XMLConverter.ToXml(obj, null, includetype);

            if(indent) {
                return xml.ToString(); 
            }
            else
            { 
                return xml.ToString(SaveOptions.DisableFormatting);
            }

        }
        else
        {
            System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringBuilder sbuilder = new StringBuilder();
            var xmlws = new System.Xml.XmlWriterSettings() { OmitXmlDeclaration = true, Indent = indent };

            ns.Add(string.Empty, string.Empty);

            using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
            {
                xs.Serialize(writer, obj, ns);
            }

            string result = sbuilder.ToString();

            ns = null;
            xs = null;
            sbuilder = null;
            xmlws = null;

            return result;
        }
    }

    private static string ToJSON<T>(T obj)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            string result = string.Empty;
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            ser.WriteObject(ms, obj);
            result = encoding.GetString(ms.ToArray());

            ms.Close();
            encoding = null;
            ser = null;

            return result;
        }
    }

}

[DataContract()]
public enum CommunicationType : int
{
    [XmlEnum("0"), EnumMember(Value = "0")]
    XML = 0,

    [XmlEnum("1"), EnumMember(Value = "1")]
    JSON = 1
}

[DataContract(Namespace = "")]
public partial class AppData
{
    [DataMember(Name = "ID")]
    public string ID { get; set; }

    [DataMember(Name = "Key")]
    public string Key { get; set; }

    [DataMember(Name = "Value")]
    public string Value { get; set; }

    [DataMember(Name = "ObjectType")]
    public string ObjectType { get; set; }
}


Any specific reason why you don't need the standard format?

To actually answer the question:

Since this is something that is outside of JSON syntax I can't think of a way to implement this within the default framework.

One solution would be to leverage attributes decorate the properties you want transported over the wired with a custom attribute and using Reflection cycle through the properties and output their property names as the column headers and then cycle throw the objects and write the values. Generic enough so it could be applied across other objects as well.

public class Location
{
     [JsonFooAttribute("City")]
     public string city {get;set;}
     [JsonFooAttribute("State")]
     public string state {get;set;}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜