简体   繁体   English

json使用newtonsoft序列化列表

[英]json serialize Lists with newtonsoft

I would like to use newtonsoft json serialzer to create json. 我想使用newtonsoft json serialzer创建json。 I'm totaly new in building LIST and collections, so I will ask you for help. 我是新建LIST和收藏集的新手,所以我会向您寻求帮助。 To create a simple json will work. 创建一个简单的json就可以了。 I have to build a attribute list, with a attributelist. 我必须建立一个带有属性列表的属性列表。

Maybee there is an other libary, making this easier ? Maybee还有另一个库,使之更容易吗?

I need this json: 我需要这个json:

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

So for this I startet to 所以为此我开始

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 ?
}

Your c# class model can't match with your JSON data. 您的c#类模型无法与JSON数据匹配。

There are two way can create model easily. 有两种方法可以轻松创建模型。

  1. You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model. 您可以在Visual Studio中使用Web Essentials,使用“编辑”>“选择性粘贴”>“将JSON粘贴为类”,可以更轻松地了解Json与模型之间的关系。

  2. If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class. 如果您不能使用Web Essentials,则可以代替使用http://json2csharp.com/在线JSON到Model类。

You can try to use those models to carry your JSON Format. 您可以尝试使用这些模型来携带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; }
}

You can use like this. 您可以这样使用。

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 C#在线

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

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