C#将项目添加到JSON对象

问题描述:

我有这个对象,我想添加其他日子。C#将项目添加到JSON对象

[{ 
    "stone":"5kg", 
    "years": 
    [{ 
     "year":"2017", 
     "stone":"5kg", 
     "months": 
     [{ 
      "month":"august", 
      "stone":"0.5kg", 
      "days": 
      [{ 
       "day":"14", 
       "stone":"0.1kg" 
      }] 
     }], 
     "weeks": 
     [{ 
      "week":"01", 
      "stone":"0.5kg" 
     }] 
    }] 
}] 

我有这个存储在一个文件,我反序列化,像这样:

string file = System.IO.File.ReadAllText(@"C:\Users\luuk\desktop\test1.json"); 
var _data = JsonConvert.DeserializeObject<List<Data>>(file); 

现在我想增加一天给它,但我只是不明白。 我想是这样的:

_data.Add(new Data() 
{ 

}); 

string json = JsonConvert.SerializeObject(_data); 
System.IO.File.WriteAllText(@"C:\Users\luuk\desktop\test1.json", json); 

但我只能访问年[]和石头在那里。

这些都是我的课:

public class Data 
{ 
    public string stone { get; set; } 
    public List<Years> years { get; set; } 
} 

public class Years 
{ 
    public string year { get; set; } 
    public string stone { get; set; } 
    public List<Months> months { get; set; } 
    public List<Weeks> weeks { get; set; } 
} 

public class Months 
{ 
    public string month { get; set; } 
    public string stone { get; set; } 
    public List<Days> days { get; set; } 
} 

public class Days 
{ 
    public string day { get; set; } 
    public string stone { get; set; } 
} 

public class Weeks 
{ 
    public string week { get; set; } 
    public string stone { get; set; } 
} 

所以,我怎么能添加一天的对象?

(我有翻译在我的代码全部variabels从荷兰到英国所以我有一些我忘了或一些错字的)

+0

您需要为每年的每个月或特定年份的特定月份添加一天? –

+0

到特定年份的特定月份。 (2017 - 8月) –

要添加新的一天你需要得到的年份和月份第一。这里是你如何能做到这一点:

// Update the data in one line 
_data[0].years.First(x=> x.year == "2017") // Get the year "2017" 
     .months.First(x=> x.month == "august") // Get the month "august" 
     .days.Add(new Days { day = "15", stone = "0.5kg" }); // Add a new day 

OR

// Get the year 
Years year = _data.years.First(x=> x.year == "2017"); 

// Get the month 
Months month = year.months.First(x=> x.month == "august"); 

// Add the day in the month 
month.days.Add(new Days { day = "15", stone = "0.5kg" }); 
+0

我的第一个代码块出现编译器错误:''列表'未包含“年”的定义 – mason

+1

好的,谢谢。这工作。我只需要使用'_data [0]'而不是'_data',并将所有数组都更改为列表。 –

+0

LuukWuijster很高兴它的工作!我在@mason指出错误后也更新了代码。 – Faisal

您使用的阵列。你不能将事物添加到已经初始化的数组中,它们是固定大小的。

T[]的所有数组更改为List<T>,然后您可以调用.Add()来添加项目。