1

I have problem with serialization and deserialization in JSON I've made 2 tasks to read from JSON file which looks like this:

[
  {
    "ID": 1,
    "OIB": 123456789,
    "ime": "name",
    "prezime": "surname",
    "grad": "city"
  }
]

Now I have to add another client with ID 2, with new user informations. I can read this JSON file with no problems, but I am stuck on writing into the same file.

public struct Klijent
{
    public int ID { get; set; }
    public long OIB { get; set; }
    public string ime { get; set; }
    public string prezime { get; set; }
    public string grad { get; set; }
}

"FetchClient" from JSON

public static List<Klijent> DohvatiKlijente()
{
    List<Klijent> lKlijent = new List<Klijent>();
    StreamReader klijent = new StreamReader("x");
    string sJson = "";
    using (klijent)
    {
        sJson = klijent.ReadToEnd();
        lKlijent = JsonConvert.DeserializeObject<List<Klijent>>(sJson);
    }
    return lKlijent;
}

"AddClient" to JSON

OIB -> personal identificator
ID -> should go +1 with every entry of client
grad -> city
ime -> name
prezime -> surname

public static void DodavanjeKlijenata()
{

    Console.Write("Unesite OIB klijenta: ");
    string pOIB = Console.ReadLine();
    long nullOIB = 0;
    long.TryParse(pOIB, out nullOIB);
    int id = 0;
    Console.Write("Unesite ime klijenta: ");
    string ime1 = Console.ReadLine();
    Console.Write("Unesite prezime klijenta: ");
    string prezime1 = Console.ReadLine();
    Console.Write("Unesite grad klijenta: ");
    string grad1 = Console.ReadLine();
    List<Klijent> lKlijent = DohvatiKlijente();
    foreach (var Klijent in lKlijent)
    {
        id = Klijent.ID + 1;
    }
    Klijent dKlijent = new Klijent()
    {
        ID = id,
        OIB = nullOIB,
        ime = ime1,
        prezime = prezime1,
        grad = grad1
    };

        var serializer = new JsonSerializer();

        using (var sw = new StreamWriter("x"))
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            serializer.Serialize(writer, dKlijent);
        }
}

This code does work, but it seems to delete every time my JSON file and it's format is in one line only, I would like to have it in multiple lines.

Thank you :)

0

1 Answer 1

1

There are two things that you need to do here

Ensure new Client is appended to existing list

For this you can add the new client to the List

lKlijent.Add(dKlijent);

Now you need to serialize the List, instead of lKlijent

using (JsonWriter writer = new JsonTextWriter(sw))
{
    serializer.Serialize(writer, lKlijent);
}

Formatting

For formatting you can use Formatting Settings. For example,

var serializer = new JsonSerializer() { Formatting = Formatting.Indented} ;

Additional Comments

1. Calculation of ID

Instead of calculating the new ID using the following loop,

foreach (var Klijent in lKlijent)
{
        id = Klijent.ID + 1;
}

You could use Enumerable.Last() to get the last client in the list. For example,

var id = lKlijent?.Any()!=true? 0:lKlijent.Last().ID;

2. Rewriting DohvatiKlijente method

The DohvatiKlijente method could rewritten as

public static List<Klijent> DohvatiKlijente()
{
    return JsonConvert.DeserializeObject<List<Klijent>>(File.ReadAllText("C:\\Users\\Hrvoje\\Desktop\\Polica Osiguranja MAIN\\Polica Osiguranja\\klijent.json"));
}

Similarly, writing back to file can be simplified as

var jsonString = JsonConvert.SerializeObject(lKlijent,Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(outputFilePath,jsonString);
Sign up to request clarification or add additional context in comments.

3 Comments

This has helped a lot, but id = lKlijent.Last().ID will not work if there is no clients in JSON file
But var id = lKlijent.LastOrDefault()?.ID will.
@cortex Thanks for pointing it out, i have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.