Unity data reading | (4) Json file parsing (Newtonsoft.Json, Litjson, JsonUtility, SimpleJSON)

Directory

  • 1 Introduction
  • 2. Advantages and Disadvantages
  • 3. Analysis
    • 3.1 Newtonsoft.Json
      • 3.1.1 Download address
      • 3.1.2 Advantages and Disadvantages
      • 3.1.3 Analysis
    • 3.2 listjson
      • 3.2.1 Download address
      • 3.2.2 Advantages and Disadvantages
      • 3.2.3 Analysis
    • 3.3 JsonUtility
      • 3.3.1 Advantages and Disadvantages
      • 3.3.2 Analysis
    • 3.4 SimpleJSON
      • 3.4.1 Download address
      • 3.4.2 Advantages and Disadvantages
      • 3.4.3 Analysis
  • 4. Summary

1. Preface

  • A JSON file is a plain text file used to store data and is based on a subset of JavaScript. JSON files are commonly used to store and transfer data, and to exchange information between applications. They store data in the form of key-value pairs, where the key is a string and the value can be a string, number, boolean, array, object, or null.
  • JSON files usually have a .json extension, such as example.json. In a JSON file, data is organized in a hierarchical structure that can represent nested objects and arrays. JSON files are commonly used to store configuration information, data exchange and persistent storage.
  • You can learn more about JSON at https://www.json.org.

2. Advantages and Disadvantages

  • Advantages of JSON files include:
    • Simple syntax: The syntax of JSON is very simple and easy to learn and use. It is based on a subset of JavaScript, so developers who are familiar with JavaScript can easily use JSON.
    • Clear data structure: JSON stores data in the form of key-value pairs with a clear hierarchical structure, making the data organized very clearly and easy to understand and process.
    • Lightweight: JSON files are plain text files that store relatively small amounts of data. They are lightweight and suitable for storing and transmitting large amounts of data.
    • Cross-platform support: JSON files are cross-platform and can be used on different operating systems and devices, making data sharing and exchange more convenient.
  • However, JSON files also have some disadvantages:
    • Comments not supported: JSON files do not support comments, which makes it difficult to maintain and read the code.
    • Security Issues: If you use JSON with an untrusted service or an untrusted browser, there may be security holes that make the data vulnerable.
    • Cannot be edited directly: JSON files are plain text files and cannot be edited directly in a text editor like XML files. Special tools or programming languages need to be used for parsing and editing.
    • Cannot store functions or classes: JSON can only store data and cannot store complex data structures such as functions or classes, which limits the scope of use of JSON.

3. Analysis

  • format template
{
  "name": "John",
  "age": 30,
  "married": true,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "postal_code": "10001"
  },
  "phone_numbers": [
    "555-1234",
    "555-5678"
  ],
  "career": null,
  "hobbies": ["reading", "traveling"]
}

3.1 Newtonsoft.Json

3.1.1 download address

  • Address: Newtonsoft.Json download address
  • Official website address: official website

3.1.2 Advantages and Disadvantages

  • advantage:
    • Fast parsing speed: Newtonsoft.Json’s parsing speed is very fast and is particularly suitable for processing large amounts of JSON data.
    • Supports multiple data formats: Newtonsoft.Json can parse JSON data in multiple data formats, including arrays, objects, strings, numbers, and more.
    • Strong scalability: Newtonsoft.Json provides a wealth of extension interfaces and options to facilitate developers to customize and expand.
    • Can parse complex Json without needing to be one-to-one with Json fields
  • shortcoming:
    • Unable to use IL2CPP packaging: Newtonsoft.Json does not support IL2CPP packaging, which may limit its applicability in some specific environments.
    • Parse error: When using Newtonsoft.Json to parse JSON data, if the JSON data format is incorrect, it may cause the program to crash or cause unpredictable behavior.
    • Unable to encrypt package body: Newtonsoft.Json does not support encryption of serialized data, which may lead to data leakage or tampering.

3.1.3 Analysis

  • JsonConvert.DeserializeObject(json); Parses a json string into a class object.
 Person person = JsonConvert.DeserializeObject<Person>(json);
  • JsonConvert.SerializeObject; Convert a class object into a json string
string jsonStr = JsonConvert.SerializeObject(person);

3.2 listjson

3.2.1 Download address

  • Address: litjson download address

3.2.2 Advantages and Disadvantages

  • Advantages of listjson files include:
    • Lightweight and efficient: LitJson’s core library is very small and has no external dependencies, so it can be loaded and used quickly. Additionally, LitJson is very efficient at parsing and generating JSON data and can handle large amounts of JSON data without causing performance issues.
    • Supports multiple data types: LitJson supports common JSON data types, such as strings, numbers, Boolean values, arrays, and objects. This makes it capable of meeting most JSON data processing needs.
    • Easy to use: LitJson’s API is designed to be very simple and easy to use, allowing developers to easily serialize and deserialize JSON data. It provides easy-to-use functions and methods, as well as intuitive encapsulation and manipulation of JSON data.
    • Powerful serialization function: LitJson provides a powerful serialization function that can serialize C# objects into JSON data and supports deserializing JSON data into C# objects. This allows developers to easily convert data between C# objects and JSON data.
  • shortcoming:
    • Custom properties not supported: While LitJson supports serializing most C# objects to JSON data, it does not support serializing custom properties to JSON. This means that if your C# object contains custom properties, LitJson may not serialize them correctly.
    • The key in the JSON string also needs to be exactly the same as the name of the class field. If they do not correspond, the parsing will fail.
    • No cross-platform support: Due to the cross-platform nature of Unity, LitJson may not be available on all platforms. This may limit its applicability in certain circumstances.
    • Possible memory leak: When using LitJson, if serialization and deserialization of JSON data are performed frequently, memory leaks may occur. This is mainly due to Unity’s memory management mechanism, but it can be solved with proper memory management and usage.

3.2.3 Analysis

  • JsonMapper.ToObject(json): Parse a json string into a class object
 Person person = JsonMapper.ToObject<Person>(str);
 // Parse json string
  JsonData jsonData = JsonMapper.ToObject(jsonStr);
   // Get data based on json object name
   Debug.Log("name = " + (string)jsonData["name"]);
  • JsonMapper.ToJson: Convert a class object into a json string
 string jsonStr = JsonMapper.ToJson(persion);

3.3 JsonUtility

3.3.1 Advantages and Disadvantages

  • advantage:
    • Efficient: JsonUtility serializes and deserializes JSON data very quickly, and is especially suitable for processing large amounts of JSON data.
    • Easy to use: JsonUtility’s API is simple and easy to use, making it convenient for developers to serialize and deserialize JSON data.
    • Does not depend on third-party libraries: JsonUtility does not depend on any third-party libraries and can be used independently.
  • shortcoming:
    • Custom properties not supported: JsonUtility does not support serializing and deserializing custom properties to JSON. This means that if your C# object contains custom properties, JsonUtility may not serialize these properties correctly.
    • The key of the Json string needs to be exactly the same as the name of the class field
    • No cross-platform support: Due to the cross-platform nature of Unity, JsonUtility may not be available on all platforms. This may limit its applicability in certain circumstances.
    • Limited support for List and Dictionary: JsonUtility cannot directly serialize and deserialize List and Dictionary, they need to be wrapped into a class to operate.

3.3.2 Analysis

  • JsonUtility.FromJson(json); Parses a json string into a class object.
 Person person= JsonUtility.FromJson<Person>(json);
  • JsonUtility.ToJson; Convert a class object into a json string.
string jsonStr= JsonUtility.ToJson(person);

3.4 SimpleJSON

3.4.1 download address

  • Address: SimpleJSON download address

3.4.2 Advantages and Disadvantages

  • advantage:
    • Small size: SimpleJSON’s source code is very concise, without too many class libraries and dependencies, so it is very small and can be quickly integrated into projects.
    • Fast: SimpleJSON is very fast when parsing and generating JSON, and can handle large amounts of JSON data efficiently.
    • Easy to integrate: SimpleJSON can be integrated into the project with just a few lines of code, without excessive configuration and settings.
    • Supports common JSON operations: SimpleJSON supports common JSON operations, such as serialization, deserialization, query, etc.
  • shortcoming:
    • Complex JSON format is not supported: SimpleJSON only supports simple JSON format, and some complex JSON formats may not be parsed correctly.
    • Cannot directly convert JSON objects to XML: SimpleJSON does not provide the function of directly converting JSON objects to XML, and manual conversion is required.
    • No complete documentation: SimpleJSON does not provide complete documentation. You need to refer to the source code and sample code when using it.

3.4.3 Analysis

  • JSON.Parse(string str);
JSONNode node = JSON.Parse(str);
var Nmae = node["Nmae"].Value;
var age = node["age"].AsFloat;
  • new JSONObject() and new JSONArray();
 JSONNode nodeRoot = new JSONObject();
        JSONNode node1 = new JSONArray();
        for (int i = 0; i < books.Count; i + + )
        {<!-- -->
            JSONNode node0 = new JSONObject();
            node0.Add("Name", books[i].name);
            node1.Add(node0);
        }
        nodeRoot.Add("Preson", node1);

4. Summary

  • Parsing time: Newtonsoft.Json is often considered one of the fastest JSON libraries, especially when it comes to processing large JSON data. Litjson also has faster parsing speed, but may be slightly slower than Newtonsoft.Json. JsonUtility and SimpleJSON may not be as good as the previous two in terms of parsing time, especially when dealing with large or complex JSON data.
  • Memory footprint: Newtonsoft.Json and Litjson generally take up more memory because they provide rich functionality and flexibility, but this also means they can handle more complex JSON data. JsonUtility and SimpleJSON may be more lightweight in terms of memory usage and are suitable for scenarios where memory consumption is limited.
  • Ease of use: Newtonsoft.Json and Litjson provide rich APIs and functions, making them easy to use and flexible in processing various JSON data. JsonUtility is built into the Unity engine, so it is very convenient to use in Unity projects. SimpleJSON is also relatively easy to use and is especially suitable for processing simple JSON data.
  • Function richness: Newtonsoft.Json and Litjson provide rich functions, including serialization, deserialization, query, operation, etc. of JSON data. JsonUtility has relatively few functions and is mainly used for basic JSON operations. SimpleJSON also provides some simple JSON operation functions, but its functions are more limited compared to Newtonsoft.Json and Litjson.
  • Overall, both SimpleJSON and LitJson are good choices if you don’t need to deal with very large JSON data. If you need to process more complex JSON data, or have high performance requirements, consider using Newtonsoft.Json or JsonUtility.