温馨提示×

c# litjson如何解析复杂JSON结构

c#
小樊
140
2024-06-24 10:38:35
栏目: 编程语言

在C#中,可以使用LitJSON库来解析复杂的JSON结构。以下是一个简单的示例代码,演示如何使用LitJSON解析一个包含嵌套结构和数组的JSON:

using LitJson;
using System;

class Program
{
    static void Main()
    {
        string json = @"
        {
            ""name"": ""John Smith"",
            ""age"": 30,
            ""isMarried"": true,
            ""children"": [
                {
                    ""name"": ""Alice"",
                    ""age"": 5
                },
                {
                    ""name"": ""Bob"",
                    ""age"": 3
                }
            ],
            ""address"": {
                ""street"": ""123 Main St"",
                ""city"": ""New York"",
                ""zipCode"": ""10001""
            }
        }";

        JsonData data = JsonMapper.ToObject(json);

        string name = (string)data["name"];
        int age = (int)data["age"];
        bool isMarried = (bool)data["isMarried"];

        JsonData children = data["children"];
        foreach (JsonData child in children)
        {
            string childName = (string)child["name"];
            int childAge = (int)child["age"];
            Console.WriteLine("Child: {0} ({1} years old)", childName, childAge);
        }

        JsonData address = data["address"];
        string street = (string)address["street"];
        string city = (string)address["city"];
        string zipCode = (string)address["zipCode"];

        Console.WriteLine("Name: {0}", name);
        Console.WriteLine("Age: {0}", age);
        Console.WriteLine("Married: {0}", isMarried);
        Console.WriteLine("Address: {0}, {1}, {2}", street, city, zipCode);
    }
}

在这个示例中,首先将JSON字符串转换为JsonData对象,然后通过索引访问对象的属性和数组元素,从而获取JSON中的数据。通过递归访问嵌套结构和数组,可以方便地解析复杂的JSON数据。

0