简体   繁体   中英

Best way to serialize a complex JSON string?

I'm struggling with a JSON string.. It contains information about LEDs and their colors. What is the fastest way to serialize this string in a structured class object?

{ "layer1": { "left": { "0": { "r": 11, "g": 10, "b": 10 }, "1": { "r": 13, "g": 13, "b": 12 }, "2": { "r": 28, "g": 25, "b": 21 } }, "top": { "0": { "r": 33, "g": 30, "b": 26 }, "1": { "r": 42, "g": 37, "b": 32 }, "2": { "r": 34, "g": 30, "b": 26 }, "3": { "r": 14, "g": 13, "b": 12 } } } }

Prefered outcome would be a SideClass (left, or top etc.) with a List.. and for every Led a R, G, and B int.

I hope someone can help me out!

Kind regards, Niels

First create the following data classes:

[DataContract]
public class MyObject
{
    [DataMember]
    public Layer layer1 { get; set; }
}
[DataContract]
public class Layer
{
    [DataMember]
    public Side left { get; set; }
    [DataMember]
    public Side top { get; set; }
}

[DataContract]
public class Side
{
    [DataMember(Name="0")]
    public Color _0 { get; set; }
    [DataMember(Name = "1")]
    public Color _1 { get; set; }
    [DataMember(Name = "2")]
    public Color _2 { get; set; }
    [DataMember(Name = "3")]
    public Color _3 { get; set; }
}
[DataContract]
public class Color
{
    [DataMember]
    public byte r { get; set; }
    [DataMember]
    public byte g { get; set; }
    [DataMember]
    public byte b { get; set; }
}

Next use the DataContractJsonSerializer to deserialize the json:

DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(MyObject));
var instance = s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));

Note that JSON doesn't make this easy if you have more sides or layers. Because the JSON doesn't use arrays but objects, it's not possible to make them returned as lists or support an arbitrary number of entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM