Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize Json when number of objects is unknown

I have a Json string:

{
    "B" : 
    {
        "JackID" : "1",
        "Faction" : "B",
        "Regard" : "24",
        "Currency" : "1340",
        "factionName" : "Buccaneer",
        "factionKing" : "22",
        "Tcurrency" : "0",
        "currencyname" : "Pieces of Eight",
        "textcolor" : "#FFFFFF",
        "bgcolor" : "#000000"
    },
    "P" : 
    {
        "JackID" : "1",
        "Faction" : "P",
        "Regard" : "20",
        "Currency" : "250",
        "factionName" : "Privateer",
        "factionKing" : "4",
        "Tcurrency" : "0",
        "currencyname" : "Privateer Notes",
        "textcolor" : "#000000",
        "bgcolor" : "#FFFF00"
    },
    "N" : 
    {
        "JackID" : "1",
        "Faction" : "N",
        "Regard" : "12",
        "Currency" : "0",
        "factionName" : "Navy",
        "factionKing" : "7",
        "Tcurrency" : "0",
        "currencyname" : "Navy Chits",
        "textcolor" : "#FFFFFF",
        "bgcolor" : "#77AADD"
    },
    "H" : 
    {
        "JackID" : "1",
        "Faction" : "H",
        "Regard" : "-20",
        "Currency" : "0",
        "factionName" : "Hiver",
        "factionKing" : "99",
        "Tcurrency" : "0",
        "currencyname" : "",
        "textcolor" : "#000000",
        "bgcolor" : "#CC9900"
    }
}

I'm using James Newton-King's Json.NET parser and calling:

JackFactionList jackFactionList = JsonConvert.DeserializeObject<JackFactionList>(sJson);

Where my classes are defined as follows:

namespace Controller
{
    public class JackFactionList
    {
        public JackFaction B;
        public JackFaction P;
        public JackFaction N;
        public JackFaction H;
    }

    public class JackFaction
    {
        public int JackId { get; set; }
        public string Faction { get; set; }
        public int Regard {get; set;}
        public int Currency {get; set;}
        // Faction details
        public string factionName {get; set;}
        public string factionKing {get; set;}
        public int Tcurrency {get; set;}
        public string currencyname {get; set;}
        public string textcolor {get; set;}
        public string bgcolor {get; set;}
    }
}

This all works, but the original list might have different JackFactions rather than B, P, N and H. Ideally what I'd like to get is:

public class JackFactionList
{
    public List<JackFaction> factionList;
}

Without changing the Json string, how can I get the JackFactions as a list rather than individual objects?

like image 749
Dave Avatar asked Feb 25 '14 10:02

Dave


1 Answers

You can serialize it as a dictionary:

var jackFactionList = JsonConvert.DeserializeObject<Dictionary<string,JackFaction>>(sJson);

Then you can get the the values:

List<JackFaction> result = jackFactionList.Values.ToList();
like image 162
Ufuk Hacıoğulları Avatar answered Sep 28 '22 10:09

Ufuk Hacıoğulları