简体   繁体   English

需要帮助反序列化 WPF 中的字典 Json

[英]Need help deserializing dictionary Json in WPF

I'm trying to parse a Json string and put a section into a dictionary.我正在尝试解析 Json 字符串并将一个部分放入字典中。 I'm running into a problem where trying to deserialize into a dictionary expects "key" and "value" terms, which are unavailable to me.我遇到了一个问题,试图反序列化成字典需要“键”和“值”术语,这对我来说是不可用的。 Can anyone recommend a workaround for me please?任何人都可以为我推荐一个解决方法吗? I prefer to stick to DataContractJsonSerializer if possible.如果可能的话,我更喜欢坚持使用 DataContractJsonSerializer。 Thank you very much in advance.非常感谢您提前。

{ "boxes": 2, "box": [ { "apples": "6", "bananas": "3", "oranges": "4", "lemons": "2" }, { "peaches": "4", "limes": "5", "melons": "5", "apples": "2" } ] } {“盒子”:2,“盒子”:[{“苹果”:“6”,“香蕉”:“3”,“橙子”:“4”,“柠檬”:“2”},{“桃子” :“4”,“酸橙”:“5”,“瓜”:“5”,“苹果”:“2”}]}

I highly recommend looking into JSON.NET .我强烈建议研究JSON.NET It's a fully featured and robust library that is the best way (in my opinion) to handle JSON in any .NET application.这是一个功能齐全且功能强大的库,是(在我看来)在任何 .NET 应用程序中处理 JSON 的最佳方式。

There is also a JSON serialization library shipped with C# driver for MongoDB.还有一个 JSON 序列化库随 MongoDB 的 C# 驱动程序一起提供。 You can start reading about it here你可以在这里开始阅读

You can also use the fast and lightweight ServiceStack's Json Serializer to handle this for you, it allows you to deserialize strongly-typed POCO's or dynamically using JsonObject:您还可以使用快速且轻量级的 ServiceStack 的 Json 序列化程序来为您处理此问题,它允许您反序列化强类型 POCO 或动态使用 JsonObject:

Using Strong-Typed POCO使用强类型 POCO

var fruitsJson = "{ \"boxes\": 2, \"box\": [ { \"apples\": \"6\", \"bananas\": \"3\", \"oranges\": \"4\", \"lemons\": \"2\" }, { \"peaches\": \"4\", \"limes\": \"5\", \"melons\": \"5\", \"apples\": \"2\" } ] }";

public class Fruits
{
    public int boxes { get; set; }
    public List<Dictionary<string,string>> box { get; set; }
}

var fruits = fruitsJson.FromJson<Fruits>();

Dynamically using JsonObject动态使用 JsonObject

var jsonObj = JsonObject.Parse(fruitsJson);
var boxes = jsonObj["boxes"];
var box = jsonObj["box"].FromJson<List<Dictionary<string,string>>>();

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

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