英文:
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 = "[{\"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);
答案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<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; }
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论