通过属性c#获取json属性

时间:2016-11-28 07:37:02

标签: c# json

我有一个类似下面的Json对象。

"log": {
    "Response": [
      {
        "@type": "Authentication",
         "Status": "True",
        "Token": "cc622e9c-0d56-4774-8d79-543c525471b4"
},
{
        "@type": "GetApplication",
        "AppId": 100,
        "Available": "True"
}]}

我需要访问appId属性。我尝试了下面的代码,它给出了空引用错误。请帮我弄清楚错误。

 dynamic JsonText = JObject.Parse(result);
 string AppId= JsonText ["log"]["Response @type='GetApplication'"]["AppId"].Tostring();

5 个答案:

答案 0 :(得分:1)

此处dotNetFiddle

          string json = @"{
    ""log"": {

        ""Response"": [{
            ""@type"": ""Authentication"",
            ""Status"": ""True"",
            ""Token"": ""cc622e9c-0d56-4774-8d79-543c525471b4""

        }, {
            ""@type"": ""GetApplication"",
            ""AppId"": 100,
            ""Available"": ""True""
        }]
    }
}";

            JObject result = JObject.Parse(json);

            foreach(var item in result["log"]["Response"])
            {
                Console.WriteLine(item["@type"]);
                Console.WriteLine(item["AppId"]);
            }

您不需要使用动态,使用JObject并在回复后的循环中使用@type

答案 1 :(得分:1)

要像您在示例中所示的那样访问AppId媒体资源:

string AppId = JObject.Parse(result)["log"].SelectToken("$.Response[?(@.@type=='GetApplication')]")["AppId"].ToString();

答案 2 :(得分:1)

string json = @"{
    ""log"": {

        ""Response"": [{
            ""@type"": ""Authentication"",
            ""Status"": ""True"",
            ""Token"": ""cc622e9c-0d56-4774-8d79-543c525471b4""

        }, {
            ""@type"": ""GetApplication"",
            ""AppId"": 100,
            ""Available"": ""True""
        }]
    }
}";

JObject obj = JObject.Parse(result);
string AppId = obj["log"]["Response"][1]["AppId"].ToString();
Console.WriteLine(AppId);

@ user3064309嗨,if(" @ type":" GetApplication")是第二个而不是更改位置。所以可以使用obj [" log"] ["响应"] [1] [" AppId"]。ToString();

答案 3 :(得分:0)

您可以使用http://json2csharp.com/生成模型类,使用Newtonsoft.Json和LINQ获取ID,如我所示。

模型类

public class Response
{   [JsonProperty("@type")]
    public string Type { get; set; }
    [JsonProperty("Status")]
    public string Status { get; set; }
    [JsonProperty("Token")]
    public string Token { get; set; }
    [JsonProperty("AppId")]
    public int? AppId { get; set; }
    [JsonProperty("Available")]
    public string Available { get; set; }
}

public class Log
{
    public List<Response> Response { get; set; }
}

public class RootObject
{
    public Log log { get; set; }
}

的.cs

   var  results = JsonConvert.DeserializeObject<RootObject>(json);
   var id=    results.log.Response.FirstOrDefault(d => d.Type == "GetApplication").AppId;

答案 4 :(得分:0)

我写了一个扩展功能,它将是深度的第三层。您可以根据需要将其深度设为通用,因此下面的代码

public static object GetJsonPropValue(this object obj, params string[] props)
{
    try
    {
        var jsonString = obj.ToString().Replace("=", ":");
        var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);
        foreach (var o in objects)
        {
            JObject jo = JObject.Parse("{" + o.ToString().Replace("=", ":") + "}");

            if (props.Count() == 1 && jo.SelectToken(props[0]) != null)
                return jo.SelectToken(props[0]).ToString();

            if (props.Count() == 2 && jo.SelectToken(props[0])?.SelectToken(props[1]) != null)
                return jo.SelectToken(props[0])?.SelectToken(props[1]).ToString();

            if (props.Count() == 2 && jo.SelectToken(props[0])?.SelectToken(props[1])?.SelectToken(props[2]) != null)
                return jo.SelectToken(props[0])?.SelectToken(props[1])?.SelectToken(props[2]).ToString();
        }
    }
    catch (Exception ex)
    {
        throw new ArgumentException("GetJsonPropValue : " + ex.Message);
    }
    return null;
}

我也为普通的c#对象编写了一个扩展,可以动态获取prop值

public static object GetPropValue(this object obj, Type typeName, string propName)
{
    try
    {
        IList<PropertyInfo> props = new List<PropertyInfo>(typeName.GetProperties());

        foreach (PropertyInfo prop in props)
        {
            if (prop.Name == propName)
            {
                object propValue = prop.GetValue(obj, null);
                return propValue;
            }
        }
    }
    catch (Exception ex)
    {
        throw new ArgumentException("GetPropValue : " + ex.Message);
    }
    return null;
}