kkost
kkost

Reputation: 3760

How to parse JSON array with different structure of JSONs into List<string>?

All the solutions that I have found to this, not satisfied with me, because I do not have JSON same structure. My JSON array:

string str = @"[{
    "type": "text",
    "field": [
        "tags",
        "track_title"
    ],
    "value": "hero",
    "operation": "must"
},  {
    "type": "range",
    "field": "duration",
    "value": [
        0,
        5
    ],
    "operation": "must"
}, {
    "type": "range",
    "field": "duration",
    "value": [
        180,
        null
    ],
    "operation": "must"
}]"

As you can see, JSONs are different. So I can't using specific model class for convert via it. I need to receive List<string> with separate JSON. How can I parse it ?

Upvotes: 0

Views: 310

Answers (2)

Triet Doan
Triet Doan

Reputation: 12085

Base on what I understand, I suggest we do this manually. Here is the code:

            string str = @"[{
    'type': 'text',
    'field': [
        'tags',
        'track_title'
    ],
    'value': 'hero',
    'operation': 'must'
},  {
    'type': 'range',
    'field': 'duration',
    'value': [
        0,
        5
    ],
    'operation': 'must'
}, {
    'type': 'range',
    'field': 'duration',
    'value': [
        180,
        null
    ],
    'operation': 'must'
}]";
            // Remove 2 brackets []
            str = str.Remove(0, 1);
            str = str.Remove(str.Length - 1, 1);

            // Split string
            string[] delimiter = {"},"};
            string[] data = str.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

            // The list you want
            List<string> result = new List<string>();

            // Turn the array into List with some modification
            foreach (string s in data)
            {
                string tmp = s;
                if (!s.EndsWith("}"))
                {
                    tmp = s + "}";
                }
                result.Add(tmp.Trim());
            }

            // Display data
            foreach (string s in result)
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();
        }

The code is self-explained. Please let me know if you find something unclear.

Upvotes: 1

tede24
tede24

Reputation: 2354

Basically what you can do is deserialize Json to a dynamic type so it can handle the differences. For example here you have how to do it with Json.Net library

Upvotes: 1

Related Questions