簡體   English   中英

如何將一組JSON對象轉換為C#列表

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

我有一個看起來像這樣的JSON文件:

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

我想將此反序列化為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; }
}

使用這樣的代碼進行轉換無法正常工作,因為pets內部有多個對象,並且不是JSON數組。

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

這是例外:

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.

有沒有一種方法可以將pets對象內部的對象轉換為對象數組? (除了將JSON本身傳遞給DeserializeObject方法之前,還需要對其進行編輯)

這是構造錯誤的json。 但是,您可以使用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; }
}

您的JSON文件包含寵物字典,而不是數組。 因此,更改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();
}

您的json 沒有“對象數組” 它說,它有一個pets與對象dogcat的特性。 所以像這樣:

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);   

    }
}

嗯...

如何轉換列表<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# 中的對象列表 將json轉換為c#對象列表 將JSON字符串轉換為C#中的動態對象列表 如何將json轉換為列表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> 如何在 C# 中將列表轉換為 JSON? 如何在C#中將JSON響應轉換為列表? 如何將JSON數組轉換為C#列表? 如何在c#中將Json字符串轉換為List 如何在C#中將Json數組轉換為列表
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM