Home > Backend Development > C++ > How to Extract Data from a JSON Array Using Json.net?

How to Extract Data from a JSON Array Using Json.net?

Barbara Streisand
Release: 2025-01-24 15:22:10
Original
618 people have browsed it

How to Extract Data from a JSON Array Using Json.net?

Use Json.net to parse JSON

Access specific JSON data

Consider the following JSON format:

<code class="language-json">{
    "displayFieldName": "OBJECT_NAME", 
    "fieldAliases": {
        "OBJECT_NAME": "OBJECT_NAME", 
        "OBJECT_TYPE": "OBJECT_TYPE"
    }, 
    "positionType": "point", 
    "reference": {
        "id": 1111
    }, 
    "objects": [ {
        "attributes": {
            "OBJECT_NAME": "test name", 
            "OBJECT_TYPE": "test type"
        }, 
        "position": {
            "x": 5, 
            "y": 7
        }
    } ]
}</code>
Copy after login

To extract only the data in the "objects" array, you can use Json.net to deserialize JSON into .NET objects:

Use Json.net

<code class="language-csharp">Foo foo = JsonConvert.DeserializeObject<Foo>(json);</code>
Copy after login

Define the following classes to match JSON structures:

<code class="language-csharp">public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}

public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}

public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}

public class Foo
{
    public List<SubObject> objects { get; set; }
}</code>
Copy after login

After deserialization, you can access the data in the "objects" array using the foo.objects attribute.

The above is the detailed content of How to Extract Data from a JSON Array Using Json.net?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template