如何解析动态字符串以查找其中的键值对

huangapple go评论74阅读模式
英文:

How to parse a dynamic string to find key-value pairs in it

问题

以下是翻译好的部分:

我有一个数据包,格式如下的JSON。

[{ "C74": "123" }, { "C75": "32" }, { "C76": "11" }, { "C78": "15" }]

是否可以解析成以下的C#模型?

{
   string key { get; set; }
   string value { get; set; }
}
英文:

I have a data packet in following JSON format.

[{"C74": "123"}, {"C75": "32"}, {"C76": "11"}, {"C78": "15"}]

Is it possible to parse in following C# model?

{
   string key { get; set; }
   string value { get; set; }
}

答案1

得分: 1

你的字符串不是一个 Dictionary,而是一个 Dictionary[]

因此,你需要以这种方式反序列化它并将其转换为你想要的格式。

string input = "[{\"C74\": \"123\"}, {\"C75\": \"32\"}, {\"C76\": \"11\"}, {\"C78\": \"15\"}]";
Dictionary<string, string>[] temp = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>[]>(input);
Dictionary<string, string> result = temp.Select(x => x.First()).ToDictionary(x => x.Key, x => x.Value);
英文:

your string is not a Dictionary it's a Dictionary[]

So you have to deserialize it that way and convert it into your desired format.

string input = &quot;[{\&quot;C74\&quot;: \&quot;123\&quot;}, {\&quot;C75\&quot;: \&quot;32\&quot;}, {\&quot;C76\&quot;: \&quot;11\&quot;}, {\&quot;C78\&quot;: \&quot;15\&quot;}]&quot;;
Dictionary&lt;string, string&gt;[] temp = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;Dictionary&lt;string, string&gt;[]&gt;(input);
Dictionary&lt;string, string&gt; result = temp.Select(x =&gt; x.First()).ToDictionary(x =&gt; x.Key, x =&gt; x.Value);

答案2

得分: 0

是的,您可以将其解析为一个列表,例如:

List<Item> items = JArray.Parse(json)
                         .SelectMany(ja => ((JObject)ja).Properties()
						 .Select(x => new Item { key = x.Name, 
                                                 value = (string)x.Value })
						 ).ToList();

public class Item
{
	public string key { get; set; }
	public string value { get; set; }
}
英文:

Yes, you can parse it to a List, for example

List&lt;Item&gt; items = JArray.Parse(json)
                         .SelectMany(ja =&gt; ((JObject)ja).Properties()
						 .Select(x =&gt; new Item { key = x.Name, 
                                                 value = (string)x.Value })
						 ).ToList();

public class Item
{
	public string key { get; set; }
	public string value { get; set; }
}

</details>



huangapple
  • 本文由 发表于 2023年7月10日 15:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定