如何从Json中提取特定属性

mkshixfv  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(154)

我正在获取具有多个属性的JSON数据,但我只想从中获取单个属性

[{"Name":"Test","GroupId":"UST","LocationGroupType":"Container","Locale":"en-US","ParentLocationGroup":{"Id":{"Value":4429},,"LgLevel":0,"Users":"0","Admins":"0","Devices":"221","Id":{"Value":5545},"Uuid":"-787d87c8fd3a"}]

我只想得到ParentLocationGroup,怎么做?

gxwragnw

gxwragnw1#

你的json无效。结尾没有多余的逗号或缺少结尾},并且您有重复的键名称ID。你的json应该是这样的。
[ {“Name”:“Test”,“GroupId”:“UST”,“LocationGroupType”:“容器”、“区域设置”:“en-US”,“ParentLocationGroup”:{“LgLevel”:0,“用户”:“0”,“管理员”:“0”,“设备”:“221”,“Id”:{“Value”:5545 },“Uuid”:“-787d87c8fd3a”} } ]
解决办法

public class Id
    {
        public int Value { get; set; }
    }

    public class ParentLocationGroup
    {
        public int LgLevel { get; set; }
        public string Users { get; set; }
        public string Admins { get; set; }
        public string Devices { get; set; }
        public Id Id { get; set; }
        public string Uuid { get; set; }
    }

    public class RootObject
    {
        public string Name { get; set; }
        public string GroupId { get; set; }
        public string LocationGroupType { get; set; }
        public string Locale { get; set; }
        public ParentLocationGroup ParentLocationGroup { get; set; }
    }

 string jsonString = "[{\"Name\":\"Test\",\"GroupId\":\"UST\",\"LocationGroupType\":\"Container\",\"Locale\":\"en-US\",\"ParentLocationGroup\":{\"LgLevel\":0,\"Users\":\"0\",\"Admins\":\"0\",\"Devices\":\"221\",\"Id\":{\"Value\":5545},\"Uuid\":\"-787d87c8fd3a\"}}]";

 List<RootObject> roots = JsonConvert.DeserializeObject<List<RootObject>>(jsonString);

 ParentLocationGroup parent = roots.FirstOrDefault().ParentLocationGroup;
ljsrvy3e

ljsrvy3e2#

您可以将字符串解析为JArray,然后使用JObject.Parse解析第一项

var jsonArray = JArray.Parse(jsonstring);
JObject obj = JObject.Parse(jsonArray[0].ToString());
Console.WriteLine(obj["ParentLocationGroup"]);
Console.WriteLine(obj["ParentLocationGroup"]["Id"]["Value"]);
u91tlkcl

u91tlkcl3#

使用Newtonsoft.JSON即可。

dynamic obj = JsonConvert.DeserializeObject(jsonStr);
Console.Write(obj[0].ParentLocationGroup);

注意你的json根是一个数组,因此obj[0]只获取第一个数组项。

相关问题