Read or update JSON without converting it to an object in .NET with C#

Read or update JSON without converting to an object in NET with csharp
Home » Technology » .Net » Read or update JSON without converting it to an object in .NET with C#

Table of contents

Sometimes we find ourselves in the situation where we need to update or read a JSON but, for various reasons, we don’t want to convert or parse it into a .NET C# object. In this article you’ll learn how to perform this process easily through several practical examples.

Why can’t we convert a JSON to a C# object?

This is a very interesting question because I didn’t realize, until recently when the need arose, that there are times when we won’t be able or willing to convert a JSON to an object to read or update it comfortably. Some of the scenarios where this can occur are the following:

Loss of information

First, we can lose information from the original JSON when we only know part of it but not the full data structure.

Let’s take the example that you’ve been assigned the task of receiving a JSON, updating two of its properties and sending it to another system. Furthermore, in the requirements, the only definition you’ve been given is the names of the two properties, where they are located in the JSON and their data type.

Given this scenario, if you convert the JSON to an object that only has those two properties you know, update them and send it to the other system, you will be losing the information about the unknown properties.

Let’s look at a full example of information loss:

  • Let’s assume the full JSON is as follows:
    {
      "Brand": "Toyota",
      "Model": "Corolla",
      "Year": 2022,
      "Color": "Red",
      "NumberOfDoors": 4,
      "FuelType": "Gasoline",
      "EnginePower": 120,
      "LicensePlate": "AB123CD",
      "Mileage": 25000,
      "Transmission": "Automatic"
    }
  • Now let’s assume the only properties given to us in the requirements are the first two, the brand and model; we don’t know the rest at all.
  • The first step is to convert it into an object represented by the following class:
    public class Car
    {
        public string Brand { get; set; }
        public string Model { get; set; }
    }
  • Then we simply update the object with code similar to the following:
    Car myCar = JsonSerializer.Deserialize<Car>(@"{
      ""Brand"": ""Toyota"",
      ""Model"": ""Corolla"",
      ""Year"": 2022,
      ""Color"": ""Red"",
      ""NumberOfDoors"": 4,
      ""FuelType"": ""Gasoline"",
      ""EnginePower"": 120,
      ""LicensePlate"": ""AB123CD"",
      ""Mileage"": 25000,
      ""Transmission"": ""Automatic""
    }");
    
    myCar.Brand = "Honda";
    myCar.Model = "Civic";
  • And finally we serialize and send to the external system with the following code:
    string jsonToSend = JsonSerializer.Serialize(myCar);
    Send(jsonToSend);

Well, if you do the above and debug the sent JSON you will realize that you are only sending the two properties that you know and that you have lost the rest of the information of the received object:

Excessive development time and work

Secondly, it can involve excessive development time and work if we know the full structure of the data and is very large and/or complex.

Following the previous scenario, let’s look at a full example of excessive development time and work:

  • Let’s suppose the car structure has 1,000 properties, including lists, nested properties, complex data types, etc.
  • Unlike the previous case, in the requirements, we have been given the full definition of the car data structure and we only need to update two of its properties.
  • The first step would be to create a class with all these properties well-defined through the necessary classes to avoid the loss of information we saw in the previous section.
  • The remaining steps would be exactly the same as before, that is, convert the received JSON to the defined class, update the object and serialize it to send it to the external system.

Now, let’s stop and think: Is it really worth investing time in defining a complex data structure with 1,000 properties and their corresponding classes if all we need to do is update two properties? The answer is simple: it’s not worth all the work.

How to read or update a JSON without converting it to an object

To avoid the above scenarios we’ll look at a C# code example to read or update a JSON without converting it to an object:

using System.Text.Json;
using System.Text.Json.Nodes;

internal class Program
{
    private static void Main(string[] args)
    {
        string json = @"{
          ""Brand"": ""Toyota"",
          ""Model"": ""Corolla"",
          ""Year"": 2022,
          ""Color"": ""Red"",
          ""NumberOfDoors"": 4,
          ""FuelType"": ""Gasoline"",
          ""EnginePower"": 120,
          ""LicensePlate"": ""AB123CD"",
          ""Mileage"": 25000,
          ""Transmission"": ""Automatic""
        }";

        // Parse to a JsonNode
        JsonNode rootNode = JsonNode.Parse(json);

        // Read a value
        string brand = rootNode["Brand"]?.ToString();

        // Update a value
        rootNode["Brand"] = "Honda";

        // Get modified JSON
        string modifiedJson = rootNode.ToJsonString();

        // Send the modified JSON
        Send(modifiedJson);
    }


    private static void Send(string jsonToSend)
    {
        throw new NotImplementedException();
    }
}

If we debug the previous code and analyze the information we are sending to the external system we can finally see that we haven’t lost any information when updating or reading the JSON:

And, therefore, in conclusion, we can say that using the C# code from the example we have achieved the following points:

  • We didn’t need to know the full car class, only the properties we were interested in reading or updating.
  • We saved development time since we only needed to use a few lines.
  • We didn’t lose any of the original information from the received JSON and we were also able to update and/or read it.