Get a specific value from a json structure

99封情书 提交于 2019-12-12 03:58:28

问题


I have this json:

{
    "unashamedohio": 
        {
            "id": 107537,
            "name": "UnashamedOhio",
            "profileIconId": 785,
            "revisionDate": 1439997758000,
            "summonerLevel": 30
        }
}

I want to get the field named summonerLevel.

I have tried to convert this json to a string and then search for summonerLevel, but I know that this solution is not okay.

I'm using Json.NET.


回答1:


You can use the dynamic keyword

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.unashamedohio.summonerLevel);



回答2:


I'm assuming this json is stored in a string, let's say called json... so try

string json = "...";
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
JObject innerObj = obj["unashamedohio"] as JObject;
int lolSummorLvl = (int) innerObj["summonerLevel"];



回答3:


You have a couple of possibilities (as already showed in the other answers). Another possibility would be to use the JObject and JProperty properties provided from Json.Net, in order to directly fetch the value like this:

var jsonObject = (JObject)JsonConvert.DeserializeObject(json);
var unashamedohio = (JObject)(jsonObject.Property("unashamedohio").Value);
var summonerLevel = unashamedohio.Property("summonerLevel");
Console.WriteLine(summonerLevel.Value);

Yet another possibility would be to create a typed model of the JSON structure:

public class AnonymousClass
{
    public UnashamedOhio unashamedohio { get; set; }    
}

public class UnashamedOhio
{
    public int summonerLevel { get; set; }
}

and use it to retrieve the value:

var ao = JsonConvert.DeserializeObject<AnonymousClass>(json);
Console.WriteLine(ao.unashamedohio.summonerLevel);

Both solutions print the same value: 30.

IMO you should use always typed models when possible and if you do a lot of value fetching from a JSON structures. It provides error checking in the IDE (as opposed to dynamic) which pay-offs at runtime.



来源:https://stackoverflow.com/questions/32103448/get-a-specific-value-from-a-json-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!