简体   繁体   English

如何将一组JSON对象转换为C#列表

[英]How to Convert a Set of JSON Objects to C# List

I have a JSON file that looks something like this: 我有一个看起来像这样的JSON文件:

{
    "foo": "bar",
    "pets": {
        "dog": {
            "name": "spot",
            "age": "3"
        },
        "cat": {
            "name": "wendy",
            "age": "2"
        }
    }
}

I would like to Deserialize this into a C# class: 我想将此反序列化为C#类:

public class PetObject
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public string Age { get; set; }
}

public class FooObject
{
    [JsonProperty("foo")]
    public string Foo { get; set; }

    [JsonProperty("pets")]
    public List<PetObject> Pets { get; set; }
}

Using some code like this to convert does not work since pets has multiple objects inside it, and is not a JSON Array. 使用这样的代码进行转换无法正常工作,因为pets内部有多个对象,并且不是JSON数组。

//does not work
FooObject content = JsonConvert.DeserializeObject<FooObject>(json);

Here is the Exception: 这是例外:

Newtonsoft.Json.JsonSerializationException
  HResult=0x80131500
  Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Test.PetObject]' 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<T>) 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.
Path 'pets.dog', line 4, position 10.

Is there a way to convert the objects inside the pets object into an array of objects? 有没有一种方法可以将pets对象内部的对象转换为对象数组? (Outside of just editing the JSON itself before passing it to the DeserializeObject method) (除了将JSON本身传递给DeserializeObject方法之前,还需要对其进行编辑)

This is badly constructed json. 这是构造错误的json。 However, you can deserialize it using the JsonProperty attribute as follows: 但是,您可以使用JsonProperty属性对其进行反序列化,如下所示:

class Program
{
    static void Main(string[] args)
    {
        string json = "{\"foo\": \"bar\",\"pets\": {\"dog\": {\"name\": \"spot\",\"age\": \"3\"},\"cat\": {\"name\": \"wendy\",\"age\": \"2\"}}}";
        Foo content = JsonConvert.DeserializeObject<Foo>(json);

        Console.Read();
    }
}

public class PetObject
{
   [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public string Age { get; set; }
}

public class Foo
{
    [JsonProperty("foo")]
    public string FooStr { get; set; }

    [JsonProperty("pets")]
    public Dictionary<string, PetObject> Pets { get; set; }
}

Your JSON file contains a dictionary of pets, not an array. 您的JSON文件包含宠物字典,而不是数组。 So, change the FooObject class: 因此,更改FooObject类:

public class FooObject
{
    [JsonProperty("foo")]
    public string Foo { get; set; }

    [JsonProperty("pets")]
    public Dictionary<string, PetObject> Pets { get; set; }

    // if you still need a list of pets, use this
    public List<PetObject> PetsList => Pets.Values.ToList();
}

Your json does not say an "array of objects" . 您的json 没有“对象数组” It says it has a pets object with dog and cat properties. 它说,它有一个pets与对象dogcat的特性。 So something like this: 所以像这样:

public class PetObject
{
    public string name { get; set; }
    public string age { get; set; }
}

public class Foo
{
    public string foo { get; set; }
    public Pets pets {get;set;}

}

public class Pets
{
    public PetObject dog { get; set; }
    public PetObject cat { get; set;}
}

public class Program
{
    public static void Main()
    {
        var json = "{\"foo\": \"bar\",\"pets\": {\"dog\": {\"name\": \"spot\",\"age\": \"3\"},\"cat\": {\"name\": \"wendy\",\"age\": \"2\"}}}"; 

        var content = JsonConvert.DeserializeObject<Foo>(json);

        Console.WriteLine(content.pets.dog.name);   

    }
}

Hth... 嗯...

如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#

暂无
暂无

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

相关问题 如何将 Json 数组转换为 C# 中的对象列表 - How to convert Json array to list of objects in c# 将json转换为c#对象列表 - convert json to c# list of objects 将JSON字符串转换为C#中的动态对象列表 - Convert JSON String to List of Dynamic Objects in C# 如何将json转换为列表c# - how to convert json to list c# 如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C# 如何在 C# 中将列表转换为 JSON? - How to convert a list to JSON in C#? 如何在C#中将JSON响应转换为列表? - How to convert JSON Response to a List in C#? 如何将JSON数组转换为C#列表? - How to convert a JSON array into a C# List? 如何在c#中将Json字符串转换为List - How to convert a Json string to List in c# 如何在C#中将Json数组转换为列表 - How to convert Json array to list in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM