繁体   English   中英

从 JSON 字符串中获取键值对

[英]Get key value pair from JSON string

我有一个像这样的 json 字符串

{
  [
    "EnrityList": "Attribute",
    "KeyName": "AkeyName",
    "Value": "Avalue"
  ],
  [
    "EnrityList": "BusinessKey",
    "KeyName": "AkeyName",
    "Value": "Avalue"
  ]
}

我已经序列化并得到了一个对象数组。 谁能帮我从这些对象数组中获取键值对。

您可以使用Newtonsoft.Json 中的JsonConvert将 json 反序列化为 Dictionary。

Dictionary<string, object> values = 
    JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring);

首先使用以下方法将上述字符串转换为正确的 json 格式:

str=str.Replace('[', '{');
str=str.Replace(']', '}');
//replace first occurance of {
int startPos = str.IndexOf('{');
str=str.Substring(0,startPos)+" ["+str.Substring(startPos + 1);
//replace last occurance of }
int endPos = str.LastIndexOf('}');
str=str.Substring(0,endPos)+"]";

这使得字符串

str = [{"EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"}, {"EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"} ]   

现在,由于您获得了 json 字符串,您可以轻松地使用它。
我们可以使用由给出的方法

如何在 ASP.NET 中将 JSON 反序列化为简单的 Dictionary<string,string>?

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

查看您的示例,您正在尝试接收特定类型元素的列表,因此首先,您需要一个类来表示您的数据类型。

class MyType
{    
  string  EnrityList;
  string  KeyName;
  string  Value;    
}

然后使用 DesrializeObject 方法将其存储在变量中

var values = JsonConvert.DeserializeObject<List<MyType>>(jsonstring);

暂无
暂无

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

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