C# JObject 如何读取数组中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15184430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:22:30  来源:igfitidea点击:

JObject how to read values in the array?

c#json.net

提问by user1781830

This is the json string:

这是 json 字符串:

{"d":[{"numberOfRowsAdded":"26723"}]}

{"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”中的值?

回答by Jon Skeet

You need to cast to JArray:

你需要投射到JArray

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

回答by James Newton-King

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

回答by jherax

You can cast your JObjectas a dynamicobject.
You can also cast your array to JArrayobject.

您可以将您JObjectdynamic对象转换为对象。
您还可以将数组转换为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;
}

回答by Carodice

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.

我尝试编写一个通用方法,该方法可以读取我的 json 字符串的任何部分。我在这个线程上尝试了很多答案,但它不适合我的需要。所以这就是我想出的。我在我的服务层中使用以下方法从 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 字符串中的特定属性,并将其转换为您需要的任何内容。