1

In my controller, I get a string that is JSON:

String json_string = this.Request.Content.ReadAsStringAsync().Result;

That looks something like so:

{
    "21": {"Id":21,"DisplayOrder":3, ... snip ... },
    "333":{"Id":333,"DisplayOrder":2, ... snip ... },
    "591":{"Id":591,"DisplayOrder":1, ... snip ... }
}

I don't have a say in the structure of this JSON so can't format it into something without keys. They keys aren't necessary since the ID is within the Value of that Dictionary.

In any case, how do I convert json_string in such a way that allows me to pull out the only two items I want when I iterate over the 'rows' in that structure... Id, DisplayOrder?

Like so:

int Id = row_item.Id;
int DisplayOrder = row_item.DisplayOrder;

Thanks! Eric

1 Answers1

0
string json = @"{
    ""21"": {""Id"":21,""DisplayOrder"":3},
    ""333"":{""Id"":333,""DisplayOrder"":2},
    ""591"":{""Id"":591,""DisplayOrder"":1}}";

var list = new JavaScriptSerializer()
               .Deserialize<Dictionary<string, Dictionary<string, object>>>(json)
               .Values
               .ToList();

Console.WriteLine(list[0]["Id"]); // <--21

You can also do the same thing with Json.Net

var jObj = JsonConvert
           .DeserializeObject<Dictionary<string, Dictionary<string, object>>>(json)
           .Values
           .ToList();

Console.WriteLine(jObj[0]["Id"]);

dynamic can be utilized too

var jObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json)
            .Values
            .ToList();

Console.WriteLine(jObj[0].DisplayOrder);
L.B
  • 114,136
  • 19
  • 178
  • 224