[英]JObject how to read values in the array?
This is the json string: 这是json字符串:
{"d":[{"numberOfRowsAdded":"26723"}]}
string json = DAO.getUploadDataSummary();
JObject uploadData = JObject.Parse(json);
string array = (string)uploadData.SelectToken("d");
How do I change the code to reader the values in 'numberOfRowsAdded? 如何更改代码以读取'numberOfRowsAdded中的值?
JObject uploadData = JObject.Parse(json);
int rowsAdded = Convert.ToInt32((string)uploadData["d"][0]["numberOfRowsAdded"])
You need to cast to JArray
: 你需要JArray
转换为JArray
:
string json = "{\"d\":[{\"numberOfRowsAdded\":\"26723\"}]}";
JObject parsed = JObject.Parse(json);
JArray array = (JArray) parsed["d"];
Console.WriteLine(array.Count);
You can cast your JObject
as a dynamic
object. 您可以将JObject
为dynamic
对象。
You can also cast your array to JArray
object. 您还可以将数组转换为JArray
对象。
JObject yourObject;
//To access to the properties in "dot" notation use a dynamic object
dynamic obj = yourObject;
//Loop over the array
foreach (dynamic item in obj.d) {
var rows = (int)item.numberOfRowsAdded;
}
I played around with writing a generic method that can read any part of my json string. 我玩过编写一个可以读取json字符串任何部分的泛型方法。 I tried a lot of the answers on this thread and it did not suit my need. 我在这个帖子上尝试了很多答案,但这并不符合我的需要。 So this is what I came up with. 所以这就是我提出的。 I use the following method in my service layer to read my configuration properties from the json string. 我在服务层中使用以下方法从json字符串中读取配置属性。
public T getValue<T>(string json,string jsonPropertyName)
{
var parsedResult= JObject.Parse(json);
return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
}
and this is how you would use it : 这就是你如何使用它:
var result = service.getValue<List<string>>(json, "propertyName");
So you can use this to get specific properties within your json string and cast it to whatever you need it to be. 因此,您可以使用它来获取json字符串中的特定属性,并将其转换为您需要的任何属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.