将JSON数据加载到C#类中

将JSON数据加载到C#类中

本文介绍了将JSON数据加载到C#类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON的新手,我正尝试将一些json内容转换为C#类以存储以供以后使用。我在尝试创建适合数据结构的类时遇到问题。 json内容的示例如下所示。

I'm fairly new to json, and I'm trying to convert some json content to a C# class to store it for later use. I'm having a problem trying to create a class which is suitable for the data structure. An example of the json content is shown below.

{
    "FirstItem": {
        "id": 1,
        "type": "foo",
        "colours": ["blue", "black", "green"],
        "reviews": {
            "positive": ["The best", "unbelievable", "Awesome"],
            "negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
            "neutral": ["OK", "Meh"]
        }
    },
    "SecondItem": {
        "id": 2,
        "type": "bar",
        "colours": ["red", "white", "yellow"],
        "reviews": {
            "positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
            "negative": ["Terrible", "Shocking", "abysmal"],
            "neutral": ["OK", "Standard", "Vanilla"]
        }
    }
}

编辑:

值得注意的是,这只是json数据的一小部分,我希望可以使用更大的数据集始终采用这种格式,但是 FirstItem SecondItem (名称?)将始终不同。我可能会以 MillionthItem 结尾。

It's worth noting that this is just a small sample of the json data, and I expect to be working with a much larger data set which is always in this format, however the FirstItem, SecondItem (names?) will always be different. I could potentially end up with a MillionthItem.

我创建了一个类基于我对上述json数据的有限理解。我认为这就是问题所在-基于上述json,我认为此类不适合。

I have created a class based on my limited understanding of the json data above. I think this is where the problem lies - I dont think this class is suitable based on the json above. Here's what I have.

public class Data
{
    public string name {get; set;}
    public int id {get; set;}
    public string type {get; set;}
    public string[] colours {get; set;}
    public Reviews reviews {get; set;}
}

public class Reviews
{
    public string[] positive {get; set;}
    public string[] negative {get; set;}
    public string[] neutral {get; set;}
}


将json转换为类


尝试并将其转换,我使用 JsonConvert 将数据反序列化为我创建的类的列表。例如:

Converting json to class

To try and convert this, I am using JsonConvert to deserialize the data to a List of a class which I have created. For example:

var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);

var result = JsonConvert.DeserializeObject<List<Data>>(response.Content);


异常


无法反序列化当前JSON对象(例如{ : value})放入类型'System.Collections.Generic.List`1 [namespace.class]',因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。
要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化的类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,而不是可以从JSON对象反序列化的集合类型(如数组或List)。还可以将JsonObjectAttribute添加到该类型中,以强制其从JSON对象反序列化。

Exception

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[namespace.class]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

我希望您能对理解上面的json格式,以及如何成功转换此格式

I'd appreciate some advice on understanding the json format above, and how I can successfuly convert this

dbc建议将此信息存储在字典中,这正是我所需要的这样做-这使我可以捕获名称( FirstItem SecondItem 等)作为键,其余

dbc suggested storing this information in a dictionary, which was exactly what I was needing to do - this allows me to capture the name (FirstItem, SecondItem etc.) as the key and the rest of the class Data as the value.

var result = JsonConvert.DeserializeObject<Dictionary<string, Data>>(response.Content);


推荐答案

只需复制json并执行在Visual Studio中>编辑->粘贴特殊->将Json粘贴为类-它将为您创建匹配的类结构。

Just copy your json and do Edit->Paste Special->Paste Json As Classes in Visual Studio - it will create you the matching class structure.

    public class Rootobject
    {
        public Firstitem FirstItem { get; set; }
        public Seconditem SecondItem { get; set; }
    }

    public class Firstitem
    {
        public int id { get; set; }
        public string type { get; set; }
        public string[] colours { get; set; }
        public Reviews reviews { get; set; }
    }

    public class Reviews
    {
        public string[] positive { get; set; }
        public string[] negative { get; set; }
        public string[] neutral { get; set; }
    }

    public class Seconditem
    {
        public int id { get; set; }
        public string type { get; set; }
        public string[] colours { get; set; }
        public Reviews1 reviews { get; set; }
    }

    public class Reviews1
    {
        public string[] positive { get; set; }
        public string[] negative { get; set; }
        public string[] neutral { get; set; }
    }

然后用法如下:

        var rootObject = JsonConvert.DeserializeObject<Rootobject>(jsonString);

这篇关于将JSON数据加载到C#类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:38