Luuk Wuijster
Luuk Wuijster

Reputation: 6878

C# add item to JSON object

I have this object and I want to add an other day to it.

[{
    "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"
        }]
    }]
}]

I have this stored in a file and I deserialize it like so:

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

Now I want to add a day to it but I just can't figure it out. I tried something like this:

_data.Add(new Data()
{

});

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

but I can only access years[] and stone in there.

These are my classes:

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

So how can I add an other day to the object?

(I have translated all the variabels in my code from dutch to english so there my be some that I forgot or some typo's)

Upvotes: 0

Views: 7865

Answers (2)

FAISAL
FAISAL

Reputation: 34673

You need to get the year and month first where you want to add another day. Here is how you can do that:

// 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" });

Upvotes: 4

CodeCaster
CodeCaster

Reputation: 151588

You're using arrays. You can't add things to already initialized arrays, they're fixed-size.

Change all arrays of T[] to List<T> and then you can call .Add() on them to add items.

Upvotes: 1

Related Questions