簡體   English   中英

如何在 C# 中寫入正確的 JSON 文件?

[英]How to write correct JSON file in C#?

我需要使用 8815489210788 中的 JSON 格式將以下數據寫入文本文件。括號對於有效的 JSON 格式很重要。

    {
      "id": 1,
      "houseattributes": [
        {
          "example_type": "big",
          "examplevalue": "black"
        },
        {
          "example_type": "small",
          "examplevalue": "white"
        },
        {
          "example_type": "very big",
          "examplevalue": "pink"
        },
       ...........
      ],
      "description": "some description..",
      "image": "image url...",
      "name": "house name...",
      "edition": 1
    }

使用此 Class,我讀取了輸入 Json,但格式錯誤,我必須修改為正確有效的 Json...並且我必須手動(編碼)將描述 + 圖像 url 添加到已解析的 Json。

    public class Houseattribute
    {
        public string example_type { get; set; }
        public string examplevalue { get; set; }
    }

    public class Root
    {
        public string name { get; set; }
        public int edition { get; set; }
        public List<Houseattribute> houseattributes { get; set; }
    }

我怎樣才能得到正確的 output json?

輸入 Json:

{
  "houseattributes": [
    {
      "example_type": "big",
      "examplevalue": "black"
    },
    {
      "example_type": "small",
      "examplevalue": "white"
    },
    {
      "example_type": "very big",
      "examplevalue": "pink"
    },
   .........
  ],
  "edition": 1,
  "name": "house name..."
}

更改您的 model 以包含額外的屬性:

public class Houseattribute
{
    public string example_type { get; set; }
    public string examplevalue { get; set; }
}

public class Root
{
    public int id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string image { get; set; }
    public int edition { get; set; }
    public List<Houseattribute> houseattributes { get; set; }
}

然后將你的JSON反序列化為model,填寫附加屬性,重新序列化。 JSON.NET 示例:

Root obj = JsonConvert.DeserializeObject<Root>(inputJson);
obj.id = 5;
obj.description = "Test";
obj.image = "https://www.example.com/images/myimage.jpg";
string outputJson = JsonConvert.SerializeObject(obj);

請注意,我建議更新您的屬性以遵循 Microsoft (TitleCase) 使用的命名約定。 您可以使用[JsonPropery("name")]修飾屬性(具有相同名稱的屬性存在於 JSON.NET 和 System.Text.Json 中)以確保它們正確序列化:

public class HouseAttribute
{
    [JsonProperty("example_type")]
    public string ExampleType { get; set; }
(etc.)

只需將附加字段添加到 class

public class Root
{
    public string name { get; set; }
    public int edition { get; set; }
    public List<Houseattribute> houseattributes { get; set; }
    public string image {get;set;}
    public string description {get;set;}
}

人們對這個問題感到困惑,因為您似乎能夠弄清楚如何添加 2 個字段,而不是缺少的兩個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM