【问题标题】:Modeling json with blank key value pairs使用空白键值对建模 json
【发布时间】:2021-04-19 17:03:38
【问题描述】:

我习惯于 json 键值对。我正在处理一些像这样遇到的 json 文件:

{
    "agents": "[{'last_name': 'Smith'}]",
    "contacts": "[]",
    "info": {
        "location ": "Your Home ",
        "more_info ": {
            "": {
                "": {
                    "_": "Custom message "
                }
            }
        },
       "last_updated": "June 2020",
        "status": {"category": "30 days", "name": "pending"},
       "active": "true"
    }
}

它是有效的 json,但我不确定如何定义我的模型,因此在调用 JSON 反序列化时,它不会中断。

我当前的模型如下所示:

public class MainDataObject
{
    public string agents {get; set;}
    public string contacts {get ;set;}
    public Info  info {get; set;}
}
public class Info
{
    public string location { get; set; }
    public string last_updated { get; set; }
    public string active {get; set;}
    public Status status {get; set;}
    public string more_info {get;set;}
    

}
public class Status
{
   public string category {get; set;}
   public string name {get; set;}
}

在我遇到包含 more_info 的文件之前,该应用程序运行良好。大多数文件的 more_info 为 "more_info" : "",因此我将其定义为字符串。

一旦遇到时髦的数据,它就会消失。不幸的是,这是来自另一家供应商,所以我无法更新他们的流程。有关如何纠正此问题的任何想法?

问候

【问题讨论】:

  • 你使用的是 Json.Net 还是 System.Text.Json 还是???
  • 我认为您必须编写一个自定义转换器才能手动遍历从more_info_
  • 你在 json 中有一个奇怪的 json 组合,以及带有空键的对象 - 但是像 app.quicktype.io 这样的网站会很快为你生成一些可用于反序列化此结构的类
  • 您也可以在 Visual Studio 中生成类:c-sharpcorner.com/UploadFile/pranayamr/…

标签: c# json deserialization


【解决方案1】:

我想出了一个解决方案。我不喜欢它,但它有效。我开发了两个具有不同 Info 子类的 MainDataObject(MainDataObject 和 MainDataObjectDict)。信息和信息字典。

如果我使用 MainDataObjectDict 导入 json 反序列化错误

InfoDict 中的more_info 是这样描述的。

 public Dictionary<string, Dictionary<string, Dictionary<string,string>>> more_info { get; set; }

我向我们的供应商提交了一张票,要求他们清理他们的模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多