简体   繁体   English

从 JSON 字符串中获取键值对

[英]Get key value pair from JSON string

I have a json string like我有一个像这样的 json 字符串

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

I have serialized and got an object array.我已经序列化并得到了一个对象数组。 Could anyone help me to get the key value pair from these object array.谁能帮我从这些对象数组中获取键值对。

You can use JsonConvert from Newtonsoft.Json to deserialize json into Dictionary.您可以使用Newtonsoft.Json 中的JsonConvert将 json 反序列化为 Dictionary。

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

First convert the above string in proper json format by using :首先使用以下方法将上述字符串转换为正确的 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)+"]";

This makes the string这使得字符串

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

Now, since you got the json string, you can easily work with it.现在,由于您获得了 json 字符串,您可以轻松地使用它。
we can use method as given by我们可以使用由给出的方法

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? 如何在 ASP.NET 中将 JSON 反序列化为简单的 Dictionary<string,string>?

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

Looking at your example, You are trying to receive a List of certain type of elements, So First, You will need a class to represent your data type.查看您的示例,您正在尝试接收特定类型元素的列表,因此首先,您需要一个类来表示您的数据类型。

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

Then use DesrializeObject method to store it in the variable然后使用 DesrializeObject 方法将其存储在变量中

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

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

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