我正在获取具有多个属性的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
,该怎么办?
答案 0 :(得分:2)
您的json无效。结尾没有多余的逗号或结束},并且您有重复的键名ID。您的json应该是这样的。
[{ “名称”:“测试”, “ GroupId”:“ UST”, “ LocationGroupType”:“容器”, “ Locale”:“ en-US”, “ ParentLocationGroup”:{ “ LgLevel”:0, “用户”:“ 0”, “管理员”:“ 0”, “设备”:“ 221”, “ID”: { “值”: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;
答案 1 :(得分:0)
您可以将字符串解析为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"]);
答案 2 :(得分:-1)
只需使用Newtonsoft.Json。
dynamic obj = JsonConvert.DeserializeObject(jsonStr);
Console.Write(obj[0].ParentLocationGroup);
请注意,您的json根目录是一个数组,因此obj [0]仅获得第一个数组项。