Get Value from JSON using JArray

别说谁变了你拦得住时间么 提交于 2020-01-12 07:39:08

问题


I have the following string (json format)
I have gotten from my server:

{[{"ruta": "1","division": "7"},{"ruta": "2","division": "7"},{"ruta": "3","division":"7"},{"ruta": "4","division": "7"},{"ruta": "5","division": "7"},{"ruta": "23","division": "7"}]}

I want to get each value and save them in string variables in order to save them in a data base.

For that I am trying to do as follows:

JArray jarr = JArray.Parse(result);
foreach (JObject content in jarr.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
         string tempValue = prop.Value.ToString; // This is not allowed 
         //here more code in order to save in a database
    }
}

But I can't find the way to convert the values to string.


回答1:


Use ToString(), not ToString.

ToString() is a method call; ToString is a reference to the ToString method, and can only be assigned to a compatible delegate.

You can also cast to String, since the JToken class defines a conversion:

string tempValue = (string)prop.Value;

Another option to consider is to use JSON serialization: create a class that represents the JSON data (with the same structure), and deserialize the JSON to this class. It makes the code much more readable and maintainable.




回答2:


You can directly de serialize your json using C# class(using:- http://json2csharp.com/) and not need to iterate through Json.

public class YourClass
{
  public string ruta { get; set; }
  public string division { get; set; }
}

You can de serialize

List<YourClass> yourClasslist= JsonConvert.DeserializeObject<List<YourClass>>(result.ToString());

You can do this because your Json is in structured format




回答3:


JArray jarr = JArray.Parse(result);
foreach (JObject content in jarr.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
         string tempValue = prop.Value.ToString(); // This is not allowed 
         //here more code in order to save in a database
    }
}

as for the JSON you should start from a JObject since it's surrounded by { }, or remove them from around the JSON you posted in your question




回答4:


JProperty.Value is of type JToken which has a method ToString (and not a property).

See documentation here.

The syntax should be like that:

string tempValue = prop.Value.ToString();


来源:https://stackoverflow.com/questions/23095507/get-value-from-json-using-jarray

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