Working with JSON Data in C#

JSON Processing in C#

JSON (JavaScript Object Notation) serves as a lightweight data format for information exchange between systems. Its syntax originates from JavaScript but maintains language independence, making it suitable for various platforms and network communications. JSON offers straightforward readability for humans and efficient parsing for machines.

JSON Structure Overview

JSON organizes data using these fundamental elements:

  • Key-value pairs with keys as quoted strings
  • Supported value types: numbers, strings, arrays, objects, booleans, and null
  • Objects enclosed in curly braces
  • Arrays contained within square brackets

Example structure:


{
    "staff": [
        {
            "firstName": "Sarah",
            "lastName": "Johnson"
        },
        {
            "firstName": "Michael",
            "lastName": "Chen"
        }
    ]
}

JSON Processing Methods in .NET

Using Newtonsoft.Json Libray

The Newtonsoft.Json package provides comprehensive JSON handling capabilities through various approaches:

JSON Reading with JsonReader

string jsonContent = @"{""source"" : ""input"", ""target"" : ""output""}";
JsonReader jsonReader = new JsonTextReader(new StringReader(jsonContent));

while (jsonReader.Read())
{
    Console.WriteLine($"{jsonReader.TokenType}\t{jsonReader.ValueType}\t{jsonReader.Value}");
}

JSON Writting with JsonWriter

StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonTextWriter(stringWriter);

jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("source");
jsonWriter.WriteValue("input");
jsonWriter.WritePropertyName("target");
jsonWriter.WriteValue("output");
jsonWriter.WriteEndObject();
jsonWriter.Flush();

string resultJson = stringWriter.GetStringBuilder().ToString();
Console.WriteLine(resultJson);

Object Manipulation with JObject

JObject jsonObject = JObject.Parse(jsonContent);
string[] propertyValues = jsonObject.Properties().Select(prop => prop.Value.ToString()).ToArray();

Array Processing

string arrayJson = "[{'id':'001','name':'item1'},{'id':'002','name':'item2'}]";
JArray jsonArray = (JArray)JsonConvert.DeserializeObject(arrayJson);
string secondItemName = jsonArray[1]["name"].ToString();

Nested Object Handling

string nestedJson = "{\"location\":{\"city\":\"Boston\",\"state\":\"Massachusetts\"}}";
JObject locationObject = (JObject)JsonConvert.DeserializeObject(nestedJson);
string cityName = locationObject["location"]["city"].ToString();
string stateName = locationObject["location"]["state"].ToString();

Custom Object Serialization

public class DataProcessor
{
    public string Source { get; set; }
    public string Result { get; set; }
}

DataProcessor processor = new DataProcessor() { Source = "raw", Result = "processed" };
JsonSerializer jsonSerializer = new JsonSerializer();
StringWriter outputWriter = new StringWriter();
jsonSerializer.Serialize(new JsonTextWriter(outputWriter), processor);
Console.WriteLine(outputWriter.GetStringBuilder().ToString());

StringReader inputReader = new StringReader(@"{""Source"":""raw"", ""Result"":""processed""}");
DataProcessor restoredProcessor = (DataProcessor)jsonSerializer.Deserialize(new JsonTextReader(inputReader), typeof(DataProcessor));
Console.WriteLine($"{restoredProcessor.Source}=>{restoredProcessor.Result}");

Built-in JavaScriptSerializer


DataProcessor processor = new DataProcessor() { Source = "raw", Result = "processed" };
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string serializedJson = jsSerializer.Serialize(processor);
Console.WriteLine(serializedJson);

DataProcessor deserializedProcessor = jsSerializer.Deserialize<dataprocessor>(serializedJson);
Console.WriteLine($"{deserializedProcessor.Source}=>{deserializedProcessor.Result}");
</dataprocessor>

DataContractJsonSerializer Approach


[DataContract]
public class DataProcessor
{
    [DataMember]
    public string Source { get; set; }
    [DataMember]
    public string Result { get; set; }
}

DataProcessor processor = new DataProcessor() { Source = "raw", Result = "processed" };
DataContractJsonSerializer contractSerializer = new DataContractJsonSerializer(processor.GetType());
string jsonOutput;

using (MemoryStream memoryStream = new MemoryStream())
{
    contractSerializer.WriteObject(memoryStream, processor);
    jsonOutput = Encoding.UTF8.GetString(memoryStream.ToArray());
    Console.WriteLine(jsonOutput);
}

using (MemoryStream inputStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonOutput)))
{
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(DataProcessor));
    DataProcessor restoredObject = (DataProcessor)deserializer.ReadObject(inputStream);
    Console.WriteLine($"{restoredObject.Source}=>{restoredObject.Result}");
}

Tags: C# JSON Newtonsoft.Json DataContractJsonSerializer JavaScriptSerializer

Posted on Wed, 01 Jul 2026 17:23:02 +0000 by Tomz