How to process JSON data in C#

Insert image description here

introduce

In modern software development, JSON (JavaScript Object Notation) has become one of the most commonly used data exchange formats. As a powerful programming language, C# provides a wealth of tools and technologies to process and manipulate JSON data.
This article will give you an in-depth understanding of various methods and techniques for processing JSON data in C#. We'll explore the following:

  1. How to serialize object to JSON string
  2. How to deserialize JSON string into object
  3. How to query and filter JSON
  4. How to use LINQ in C# to manipulate JSON data
  5. How to deal with complex nested JSON structures
  6. How to handle JSON data of date and time types
  7. How to handle special characters and escape sequences in JSON
  8. How to handle large amounts of JSON data
  9. How to handle exception and error conditions in JSON
  10. Best practices and performance optimization recommendations


1. Serialize object into JSON string

In C#, you can serialize objects into JSON strings using the two popular libraries System.Text.Json. Newtonsoft.JsonHere is sample code for serialization using these two libraries:

using System;
using System.Text.Json;
using Newtonsoft.Json;

public class Person
{
    
    
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

public class Program
{
    
    
    public static void Main()
    {
    
    
        Person person = new Person {
    
     Name = "John Doe", Age = 30 };

        // 使用System.Text.Json库进行序列化
        string json1 = JsonSerializer.Serialize(person);
        Console.WriteLine(json1);

        // 使用Newtonsoft.Json库进行序列化
        string json2 = JsonConvert.SerializeObject(person);
        Console.WriteLine(json2);
    }
}

Insert image description here

2. Deserialize JSON string into object

As opposed to serializing an object into a JSON string, you can also use System.Text.Jsonand Newtonsoft.Jsonto deserialize a JSON string into an object in C#. Here is sample code for deserialization using these two libraries:

using System;
using System.Text.Json;
using Newtonsoft.Json;

public class Person
{
    
    
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

public class Program
{
    
    
    public static void Main()
    {
    
    
        string json = "{\"Name\":\"John Doe\",\"Age\":30}";

        // 使用System.Text.Json库进行反序列化
        Person person1 = JsonSerializer.Deserialize<Person>(json);
        Console.WriteLine(person1.Name);
        Console.WriteLine(person1.Age);

        // 使用Newtonsoft.Json库进行反序列化
        Person person2 = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine(person2.Name);
        Console.WriteLine(person2.Age);
    }
}

3. Query and filter JSON

In C#, we can use LINQ (Language-Integrated Query) to query and filter JSON. By using SelectTokenmethods and JsonPath expressions, we can easily access and manipulate nested JSON properties. Here is an example of querying and filtering JSON using LINQ:

using System;
using Newtonsoft.Json.Linq;

public class Program
{
    
    
    public static void Main()
    {
    
    
        string json = "{\"Name\":\"John Doe\",\"Age\":30,\"Address\":{\"City\":\"New York\",\"Country\":\"USA\"}}";
        JObject obj = JObject.Parse(json);

        // 使用JsonPath表达式查询和筛选JSON
        JToken nameToken = obj.SelectToken("$.Name");
        Console.WriteLine(nameToken.Value<string>());

        JToken addressToken = obj.SelectToken("$.Address");
        Console.WriteLine(addressToken["City"].Value<string>());
        Console.WriteLine(addressToken["Country"].Value<string>());
    }
}

4. Use LINQ to operate JSON data

In addition to querying and filtering, we can also use LINQ to perform various operations on JSON data, such as projection, connection, and sorting. Here is an example of using LINQ to manipulate JSON data:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

public class Program
{
    
    
    public static void Main()
    {
    
    
        string json = "[{\"Name\":\"John Doe\",\"Age\":30},{\"Name\":\"Jane Smith\",\"Age\":35}]";
        JArray array = JArray.Parse(json);

        // 使用LINQ查询和操作JSON数据
        var names = from item in array
                    select item["Name"].Value<string>();

        foreach (string name in names)
        {
    
    
            Console.WriteLine(name);
        }
    }
}

5. Handle complex nested JSON structures

When dealing with complex nested JSON structures, you can use the JObjectand JArrayclasses to easily access and manipulate JSON data. These two classes provide a series of methods and properties for working with nested JSON objects and arrays. Here's an example of handling complex nested JSON structures:

using System;
using Newtonsoft.Json.Linq;

public class Program
{
    
    
    public static void Main()
    {
    
    
        string json = "{\"Name\":\"John Doe\",\"Age\":30,\"Address\":{\"City\":\"New York\",\"Country\":\"USA\"},\"Languages\":[\"C#\",\"JavaScript\"]}";
        JObject obj = JObject.Parse(json);

        Console.WriteLine(obj["Name"].Value<string>());
        Console.WriteLine(obj["Age"].Value<int>());
        Console.WriteLine(obj["Address"]["City"].Value<string>());
        Console.WriteLine(obj["Address"]["Country"].Value<string>());

        foreach (string language in obj["Languages"])
        {
    
    
            Console.WriteLine(language);
        }
    }
}

6. Processing JSON data of date and time types

When JSON contains date and time type data, you can use DateTimeOffsetthe and JsonConvertclasses for correct processing and conversion. Here is an example of handling JSON data of date and time types:

using System;
using Newtonsoft.Json;

public class Person
{
    
    
    public string Name {
    
     get; set; }
    public DateTimeOffset BirthDate {
    
     get; set; }
}

public class Program
{
    
    
    public static void Main()
    {
    
    
        string json = "{\"Name\":\"John Doe\",\"BirthDate\":\"1980-01-01T00:00:00+00:00\"}";

        // 使用Newtonsoft.Json处理日期和时间类型
        Person person = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine(person.Name);
        Console.WriteLine(person.BirthDate);
    }
}

7. Handle special characters and escape sequences in JSON

When dealing with JSON data that contains special characters and escape sequences, you can use JsonConvertthe class's EscapeStringmethods to perform proper escaping. Here is an example of handling JSON data with special characters and escape sequences:

using System;
using Newtonsoft.Json;

public class Program
{
    
    
    public static void Main()
    {
    
    
        string text = @"This is a \"quoted\" text.";
        string json = JsonConvert.SerializeObject(text);

        Console.WriteLine(json); // 输出:"This is a \\\\\"quoted\\\\\" text."
    }
}

8. Process large amounts of JSON data

When processing data containing large amounts of JSON, you can use the JsonReaderand JsonWriterclasses to implement streaming, thereby reducing memory usage and improving performance. Here is an example of processing large amounts of JSON data:

using System;
using System.IO;
using Newtonsoft.Json;

public class Person
{
    
    
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

public class Program
{
    
    
    public static void Main()
    {
    
    
        string[] names = {
    
    "John", "Jane", "Tom", "Alice"};

        using (var stream = new StreamWriter("data.json"))
        using (var writer = new JsonTextWriter(stream))
        {
    
    
            writer.WriteStartArray();

            foreach (string name in names)
            {
    
    
                var person = new Person {
    
    Name = name, Age = 30};
                JsonSerializer.Serialize(writer, person);
            }

            writer.WriteEndArray();
        }
    }
}

9. Handle exception and error conditions in JSON

When processing JSON data, you may encounter various exceptions and error conditions. To ensure the robustness and reliability of your code, try-catchstatements should be used to catch and handle exceptions. Here is an example of handling JSON exception and error conditions:

using System;
using Newtonsoft.Json;

public class Program
{
    
    
    public static void Main()
    {
    
    
        try
        {
    
    
            string invalidJson = "This is not a valid JSON.";
            dynamic obj = JsonConvert.DeserializeObject(invalidJson);
        }
        catch (JsonReaderException ex)
        {
    
    
            Console.WriteLine("JSON解析错误:" + ex.Message);
        }
        catch (JsonSerializationException ex)
        {
    
    
            Console.WriteLine("JSON序列化错误:" + ex.Message);
        }
    }
}

10. Best practices and performance optimization suggestions

When processing JSON data, following the following best practices and performance optimization recommendations can improve the readability and performance of your code:

  • Use System.Text.Jsonthe library when possible, it is the default JSON library for .NET Core and has a Newtonsoft.Jsonbetter performance ratio.
  • For complex nested JSON structures, use JObjectthe and JArrayclasses for access and manipulation.
  • For large amounts of JSON data, use JsonReaderthe and JsonWriterclasses for streaming.
  • Use LINQ to query and manipulate JSON data, making the code more concise and readable.
  • Avoid repeated JSON serialization and deserialization operations within loops, and try to cache the results.

Summarize

This article provides an in-depth introduction to various methods and techniques for processing JSON data in C#. We learned how to serialize objects to JSON strings, and how to deserialize JSON strings to objects. We also explored how to query, filter, and manipulate JSON data, and how to handle complex nested JSON structures, dates and times, special characters and escape sequences, large amounts of JSON data, and exception and error conditions. Finally, we provide some best practices and performance optimization recommendations.

Guess you like

Origin blog.csdn.net/qq_22120623/article/details/135081071