适合JSON格式的类 - 这可能吗?

时间:2018-03-16 01:38:49

标签: c# json json.net

我一直在尝试创建c#类来映射到服务所需的JSON格式。但未能找到正确的答案。

这是JSON:

{
  "request": {
    "path": "1",
    "coverages": {
      "path": "2",
      "broadcastCoverage": {
        "path": "3",
        "name": "First Coverage",
        "channel": "Channel 9",
        "callSign": "DSOTM"
      },
      "internetCoverage": {
        "path": "4",
        "name": "Second Coverage",
        "url": "www.stackoverflow.com"
      },
      "thirdCoverage": {
        "path": "5",
        "name": "Third Coverage",
        "differentProperty": "Units"
      }
    }
  }
}

如果我把它放到JSON到C#转换器中,我会得到以下结果:

public class BroadcastCoverage
{
    public string path { get; set; }
    public string name { get; set; }
    public string channel { get; set; }
    public string callSign { get; set; }
}

public class InternetCoverage
{
    public string path { get; set; }
    public string name { get; set; }
    public string url { get; set; }
}

public class ThirdCoverage
{
    public string path { get; set; }
    public string name { get; set; }
    public string differentProperty { get; set; }
}

public class Coverages
{
    public string path { get; set; }
    public BroadcastCoverage broadcastCoverage { get; set; }
    public InternetCoverage internetCoverage { get; set; }
    public ThirdCoverage thirdCoverage { get; set; }
}

public class Request
{
    public string path { get; set; }
    public Coverages coverages { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
}

但是我需要不同类型的Coverage(广播,互联网,其他)变量,所以我尝试从Coverages类中取出它们并添加了一个属性:

public Dictionary<string, CoverageBase> CoverageList { get; set; }

这将允许我选择要包含的覆盖范围,然后问题变为CoverageList属性名称在序列化时在JSON中。我基本上想要一个没有属性名称的键/值(字符串,CoverageBase)。

有没有办法在JSON中没有属性名称的情况下添加键值对?我已经看到了在根对象级别完成此操作的示例,但我还没有找到嵌套在JSON中的任何示例。

如果不能使用简单的对象模型,那么建立JSON的推荐方法是什么?

更新:我喜欢使用JsonSubTypes的答案,因为它不需要很多代码,但是我不能在json.net之外使用第三方库。有没有办法使用JsonConverter完成这个?

1 个答案:

答案 0 :(得分:2)

我认为它可能已经检查here,但是你的应用似乎需要以包含C#typings的格式重建json。更多文档here

修改 感谢dbc&#39; reference我能够潜入JsonSubtypes并且很容易实现。

这是我的代码库结构。

import openpyxl, pprint
from openpyxl import load_workbook
import pandas as pd
import numpy as np
import os

# The next four lines create a sample excel file called test_1.xlsx
df = pd.DataFrame(np.random.randn(15, 12), columns=list('ABCDEFGHIJKL'))
writer = pd.ExcelWriter('test_1.xlsx', engine='openpyxl')
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.close()

wb = load_workbook('test_1.xlsx')
sheet1 = wb['Sheet1']
my_list = []
for j in range(2, 8):
    my_list.append(sheet1.cell(row = 7, column = j).value)
print(my_list)

wb.create_sheet('Sheet3')
sheet3 = wb['Sheet3']
for j in range(13,19):
    sheet3.cell(row = 22, column = j).value = my_list[j-13]
wb.save("test_2.xlsx")

然而,你收到的Json结构不是很理想,所以我做了一些重新格式化,只是为了让它得到正确的解析。

[JsonConverter(typeof(JsonSubtypes))]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(BroadcastCoverage), "channel")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(InternetCoverage), "url")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(ThirdCoverage), "differentProperty")]
public class CoverageBase
{
    public string path { get; set; }
    public string name { get; set; }
}

public class BroadcastCoverage : CoverageBase
{
    public string channel { get; set; }
    public string callSign { get; set; }
}

public class InternetCoverage : CoverageBase
{
    public string url { get; set; }
}

public class ThirdCoverage : CoverageBase
{
    public string differentProperty { get; set; }
}

public class Request
{
    public string path { get; set; }
    public List<CoverageBase> coverages { get; set; }
}

Result