JObject how to read values in the array?

故事扮演 提交于 2020-05-12 11:05:08

问题


This is the json string:

{"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?


回答1:


JObject uploadData = JObject.Parse(json);
int rowsAdded = Convert.ToInt32((string)uploadData["d"][0]["numberOfRowsAdded"])



回答2:


You need to cast to JArray:

string json = "{\"d\":[{\"numberOfRowsAdded\":\"26723\"}]}";
JObject parsed = JObject.Parse(json);
JArray array = (JArray) parsed["d"];
Console.WriteLine(array.Count);



回答3:


You can cast your JObject as a dynamic object.
You can also cast your array to JArray object.

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;
}



回答4:


I played around with writing a generic method that can read any part of my json string. 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.

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.



来源:https://stackoverflow.com/questions/15184430/jobject-how-to-read-values-in-the-array

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