【问题标题】:json serialize Lists with newtonsoftjson 用 newtonsoft 序列化列表
【发布时间】:2018-07-22 19:02:52
【问题描述】:

我想使用 newtonsoft json 序列化器来创建 json。 我在构建 LIST 和集合方面完全是新手,所以我会向你寻求帮助。 创建一个简单的 json 就可以了。 我必须建立一个属性列表,带有一个属性列表。

也许还有其他库,让这更容易?

我需要这个 json:

{
    "objectTypeId": 545,
    "attributes": [{
        "objectTypeAttributeId": 222,
        "objectAttributeValues": [{
            "value": "Kommentar"
        }]
    }]
}

所以我开始了

public class Controller
{
        public int objectTypeId { get; set; }
        public IList<string> attributes { get; set; }
}

Controller controllerjson = new Controller
{
  objectTypeId = 545,
  // How to add the attributes with each values ?
}

【问题讨论】:

标签: c# json serialization json.net


【解决方案1】:

您的 c# 类模型与您的 JSON 数据不匹配。

有两种方法可以轻松创建模型。

  1. 您可以在Visual Studio中使用Web Essentials,使用Edit > Paste special > paste JSON as class,可以更容易的了解Json和model的关系。

  2. 如果您不能使用 Web Essentials,您可以使用 http://json2csharp.com/ online JSON to Model 类代替。

您可以尝试使用这些模型来承载您的 JSON 格式。

public class ObjectAttributeValue
{
    public string value { get; set; }
}

public class Attribute
{
    public int objectTypeAttributeId { get; set; }
    public List<ObjectAttributeValue> objectAttributeValues { get; set; }
}

public class RootObject
{
    public int objectTypeId { get; set; }
    public List<Attribute> attributes { get; set; }
}

你可以这样使用。

RootObject controllerjson = new RootObject()
{
    objectTypeId = 545,
    attributes = new List<Attribute>() {
        new Attribute() {
            objectTypeAttributeId = 222,
            objectAttributeValues = new List<ObjectAttributeValue>() {
                new ObjectAttributeValue() { value= "Kommentar" }
            }
        }
    }
};

string jsonStr = JsonConvert.SerializeObject(controllerjson);

c# online

【讨论】:

    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多