简体   繁体   English

Json从JSON对象C#获取数组对象

[英]Json get array object from JSON Object C#

I have this json string passed to my webapi 我有这个json字符串传递给我的webapi

 string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";

I may have more than on pair of (K,V) inside. 我的(K,V)对中可能有更多。 How do i parse this in C# ? 我如何在C#中解析呢?

I thought i could first convert my string to a JObject and get the key for datamodel from that and then use JArray to parse the K,V. 我以为我可以先将字符串转换为JObject并从中获取数据模型的密钥,然后使用JArray解析K,V。 But its throwing a jsonreader exception on the first line of code here 但它在这里的第一行代码中引发jsonreader异常

JObject my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring.ToString());

and then do this.. 然后这样做

 JObject data = my_obj["datamodel"].Value<JObject>();

First of all, the JSON string you are posting is not valid. 首先,您要发布的JSON字符串无效。 Given your comment, you can clean up the quotes before and after the square brackets using this snippet: 根据您的评论,您可以使用以下代码段清除方括号前后的引号:

string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";;
string jsonstringCleaned = jsonstring.Replace("\"[", "[").Replace("]\"", "]");
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstringCleaned);

The code is right, but the exception you are getting is related to the formatting of your JSON string. 该代码是正确的,但是您得到的异常与JSON字符串的格式有关。 If you put valid JSON in this code, it should work as expected. 如果在此代码中放入有效的JSON,则它应能按预期工作。

JSON字符串中的V1左右缺少\\“。看起来应该像这样:

string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";

First always make sure that you have a valid Json string. 首先,始终确保您具有有效的Json字符串。 A simple way to do that is paste it into a Json to C# converter tool, such as this one: http://json2csharp.com/ 一种简单的方法是将其粘贴到Json to C#转换工具中,例如: http : //json2csharp.com/

It may be simpler and more readable to use single quotes within your Json string if that is an option, as it avoids the need to escape the double quotes: 如果可以选择在Json字符串中使用单引号,可能会更简单易读,因为它避免了转义双引号的需要:

    string jsonstring = "{'datamodel': [{'K1':'V1','K2':'V2'}]}"

Now we deserialize the object and get the JArray. 现在,我们反序列化对象并获取JArray。 There is no need to call the ToString() on the JSON jsonstring string. 无需在JSON jsonstring字符串上调用ToString()。

   var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring);
   var data = (JArray)my_obj["datamodel"];

A better and more concise way to accomplish the same result could be to just use JObject.Parse. 实现相同结果的更好,更简洁的方法可能是只使用JObject.Parse。 We can accomplish the same result with just one line of code. 我们只需一行代码就可以完成相同的结果。

    var data = (JArray)JObject.Parse(jsonstring)["datamodel"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM