【问题标题】:Format each list entry with name JSON使用名称 JSON 格式化每个列表条目
【发布时间】:2020-07-16 07:05:10
【问题描述】:

我正在尝试以特定方式将 List 对象格式化为 JSON:

...

{
    "MyList": [
        "Entry": {
           "Id": "1000",
           "Name" : "Billy"
        }
    ]
}

...

我的问题是我无法为列表中的每个项目写入“条目”属性名称。

这是我的 C# 代码:

Entry.cs

[JsonObject(MemberSerialization.OptIn)]
    public class Entry
    {
        [JsonProperty]
        public string Id { get; set; }
        [JsonProperty]
        public string Name { get; set; }
    }

列表.cs

[JsonObject(MemberSerialization.OptIn)]
    public class MyList
    {
        [JsonProperty]
        List<Entry> List = new List<Entry>();

        public void Add(Entry param) {
            List.Add(param);
        }
    }

TestController.cs

[HttpPost]
    public IHttpActionResult GrabarMarcacion([FromBody] JObject data)
    {
        MyList lst = new MyList();
        lst.Add(new Entry{Id="1000", Name="Billy"});
        return Ok(lst);
    }

对不起,我是 JSON 和 REST 的新手,是否可以按照我的要求进行操作?到目前为止,我总是得到类似的东西:

{
    "List": {
        {
            "ID": "1000",
            "Name" : "Billy"
        },
        {
                    "ID": "1001",
            "Name" : "Bob"
        }
    }
}

【问题讨论】:

  • 首先,预期的 Json 看起来不是有效的 Json 格式。请确保其格式有效
  • 正如@AnuViswan 所说,您不能使用 JSON 序列化程序真正生成无效的 JSON。要么将您的期望更改为有效的 JSON,要么使用常规的文本操作来构造您喜欢的任何格式(但不要将其称为 JSON,也不希望任何人能够这样解析它)。请edit发帖澄清。

标签: c# rest asp.net-web-api2


【解决方案1】:

据我了解,您希望列表中每个项目的 Entry 属性名称。最简单的方法是将其设为Dictionary

Entry.cs重命名为EntryModel.cs

[JsonObject(MemberSerialization.OptIn)]
public class EntryModel
{
    [JsonProperty]
    public Dictionary<string, string> Entry { get; set; }
}

List.cs 中,将属性更改为MyList。这需要更改类名。

[JsonObject(MemberSerialization.OptIn)]
public class MyListModel
{
    [JsonProperty]
    public List<EntryModel> MyList { get; set; } = new List<EntryModel>();
}

现在在您的TestController.cs 中,您可以使用:

MyListModel lst = new MyListModel();
lst.MyList.Add(new EntryModel 
{
    Entry = new Dictionary<string, string> {
        { "Id", "1000" }, { "Name", "Billy" } }
});

lst.MyList.Add(new EntryModel
{
    Entry = new Dictionary<string, string> {
        { "Id", "3000" }, {"Name", "ABC" } }
});

这给出了以下 JSON:

{
  "MyList": [
    {
      "Entry": {
        "Id": "1000",
        "Name": "Billy"
      }
    },
    {
      "Entry": {
        "Id": "3000",
        "Name": "ABC"
      }
    }
  ]
}

【讨论】:

  • 这不是我所需要的,但我能够通过将我的 Entry 类包装在另一个类中来解决我的问题。然后,我声明了该包装类的列表,它最终按我的意愿工作。这给了我这个想法,所以谢谢你先生
【解决方案2】:

我从未使用过 c#,但尝试使用 Entry.cs:

[JsonObject(MemberSerialization.OptIn)]
    public class Entry
  {
  [JsonProperty]
  public object Entry { get; set; }
    {
        [JsonProperty]
        public string Id { get; set; }
        [JsonProperty]
        public string Name { get; set; }
    }
  }

【讨论】:

  • 我试过了,它说这个声明类型无效..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
相关资源
最近更新 更多