简体   繁体   中英

How to turn String (json-like) into Object

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

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);

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