skip to Main Content

Disclaimer: C# isn’t really my forte, guys; I’m usually a database guy. Alot of this is pieced together code I’ve found here and there; so please go easy on me.

I’m trying to figure out how to add a new object to an existing JSON document that a user opens and then saving the updates to that file. The below is a made up JSON that follows the same basic structure and I want to be able to add a new "car" to a "person". The "new" values are coming via textboxes and dropdowns.

{
  "Name": "Bob Bob",
  "City": "Louisville",
  "State": "Kentucky",
  "Address": "123 City Ln",
  "Cars": [
    {
      "Make": "Ford",
      "Model": "Explorer",
      "Color": "White"
    },
    {
      "Make": "Dodge",
      "Model": "Caravan",
      "Color": "White"
    },
    {
      "Make": "Bat",
      "Model": "Mobile",
      "Color": "Black:"
    }
  ],
  "Jobs": [
    {
      "Employer": "Walmart",
      "Position": "Greeter",
      "Pay": "$35,000",
      "EndDate": "12/25/1999"
    },
    {
      "Employer": "Target",
      "Position": "Cashier",
      "Pay": "$32,000",
      "EndDate": "1/1/2002"
    },
    {
      "Employer": "SkyNet",
      "Position": "Programmer",
      "Pay": "$86,000",
      "EndDate": "5/8/2023"
    }
  ]
}

I have the below classes set up

public class Person
{
    public string Name { get; set;}
    public string City { get; set;}
    public string State { get; set;}
    public string Address { get; set;}
    public Cars[] Cars {get; set;}
    public Jobs[] Jobs {get; set;}
}

public class Cars
{
    public string Make { get; set;}
    public string Model { get; set;}
    public string Color { get; set;}
}

public class Jobs
{
    public string Employer { get; set;}
    public string Position { get; set;}
    public string Pay { get; set;}
    public string EndDate { get; set;}
}

Here’s the code I have so far

private void btnSaveUpdates_Click(object sender, EventArgs e)
{
    string Make = cbMake.Text;
    string Model = txtModel.Text;
    string Color = cbColor.Text;
    string filePath = txtFileLoc.Text;

    DoJSONWork(filePath, Make, Model, Color);
}

public static void DoJSONWork(string filePath, string Make, string Model, string Color)
{
    var FileStream = File.OpenRead(filePath);

    using (StreamReader reader = new StreamReader(FileStream))
    {
        using (JsonTextReader JSONreader = new JsonTextReader(reader))
            {
                JSONreader.SupportMultipleContent = true;

                var serializer = new JsonSerializer();
                while (JSONreader.Read())
                {
                    if (JSONreader.TokenType == JsonToken.StartObject)
                    {
                        Person p = serializer.Deserialize<Person>(JSONreader);

                        Cars cars = p.Cars.FirstOrDefault(c => c.Make + c.Model + c.Color == Make + Model + Color);
                        if (cars == null)
                        {
                            cars = new Cars
                            {
                                Make = Make,
                                Model = Model,
                                Color = Color
                            };
                            p.Cars = p.Cars.Concat(new Cars[]
                            {
                              cars
                            }).ToArray();

                        }

                    }
                }
            }
        }

        //I honestly don't know what to do next 
    }

I’m struggling to figure out how to update the "cars" in the JSON document. Do I need to deserialize and serialize the entire JSON doc?

2

Answers


  1. the short answer is Yes.
    in order to manipulate a json first you should Deserialize it to a Collection of a type that c# understands after you can add data to the collection and then serialize it again the code goes something like this

    var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);

    then you can find or add an object to the list

    list.Add(new Person());

    and in the end, you must convert your list to json

    var convertedToJson = JsonConvert.SerializeObject(list);

    by the way JsonConvert is in the namespace of using Newtonsoft.Json;
    there are plenty of ways to convert.
    this package is one of the easy ones

    Login or Signup to reply.
  2. you don’t need any classes, just parse your json

        var json =File.ReadAllText(filePath);
    
        var jObj = JObject.Parse(json);
        var cars = (JArray)jObj["Cars"];
        
        if (cars == null) cars = new JArray();
        else if (cars.Any(c => ((string)c["Make"]) == Make
                                    && ((string)c["Model"]) == Model
                                     && ((string)c["Color"]) == Color)) 
                                    return;
        cars.Add(new JObject
        {
    
            ["Make"] = Make,
            ["Model"] = Model,
            ["Color"] = Color
        });
        
        json=jObj.ToString();
        
        File.WriteAllText(filePath, json);
    

    or you can use Cars class, since you have it already

        var jObj = JObject.Parse(json);
    
        List<Cars> cars = jObj["Cars"].ToObject<List<Cars>>();
    
        if (cars.Any(c => c.Make + c.Model + c.Color == Make + Model + Color)) return;
    
        cars.Add(new Cars
        {
            Make = Make,
            Model = Model,
            Color = Color
        });
    
        jObj["Cars"] = JArray.FromObject(cars);
    
        json = jObj.ToString();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search