简体   繁体   中英

Getting element name in a JSON file

I have a given JSON file (json):

{ "people":{ "name":{ "Senior":{ "name": "Jan",
"country": "US" }, "Junior":{ "name": "George", "country": "CA" } } } }

This is made after a example of the Local State file found in

C:\\Users\\username\\Local\\Google\\Chrome\\User Data\\Local State

I want the output like this:

Senior  
Name: Jan  
Country: US  

Junior  
Name: George  
Country: CA

The code I wrote so far:

StringBuilder workLog = new StringBuilder();  
using (StringReader reader = new StringReader(json))
using (JsonReader jsonReader = new JsonTextReader(reader))
 {
 JsonSerializer serializer =  new JsonSerializer();
 var obj = (JToken)serializer.Deserialize(jsonReader);
 //
 var ids = obj["people"]["name"]; 
 foreach (var profile in ids)
  {
  // profile.Name doesn't work, so I guess I need 
  // something here to get the Senior and Junior...
  foreach (var userdata in profile)
   {
   try
    {
     string name = (string)userdata["name"];
     string country=(string)userdata["country"];
     workLog.AppendLine("Profile: " + "[ " + name + " ]" + " country " +   country + Environment.NewLine);
    }
    catch (JsonException je)
    {
     MessageBox.Show(je.Message);
    }
    catch (NullReferenceException nr)
    {
    // todo
    }
   }
  }
}  

How do I get the "Senior" and "Junior" ?

Updated the jason string with curleys at the begin and end.

Code

The sample is running here .

using System;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        dynamic result = JObject.Parse(json);
        var obj1 = result.people.name;
        foreach (var prop1 in obj1)
        {
            Console.WriteLine(prop1.Name);
            foreach (var obj2 in prop1)
            {
                foreach (var prop2 in obj2)
                {
                    Console.WriteLine(prop2.Name + ": " + prop2.Value);
                }
            }
        }
    }
}

It uses the JSON string that you posted.

    private static string json = @"


{
    ""people"": {
        ""name"": {
            ""Senior"": {
                ""name"": ""Jan"",
                ""country"": ""US""
            },
            ""Junior"": {
                ""name"": ""George"",
                ""country"": ""CA""
            }
        }
    }
}

    ";

Output

Senior
name: Jan
country: US
Junior
name: George
country: CA

Your JSON input is wrong, it should start and end with angle brackets.

Json has 2 main container types, objects (have fields) and arrays (have objects or primitives such as int, float, string). Objects start with { and end with }, arrays start with [ and end with ]. And you can nest how many you want inside each other. Lists of things should be inside an array and groups of things (like properties of a person) inside objects.

Try the following JSON format :

    {
      "people":[
        {
            "name":[ 
                {"Senior":{ "name": "Jan", "country": "US" } },
                {"Junior":{ "name": "George", "country": "CA" } }
            ]
        }
      ]
    }

This will give you an object with a single field called "people" of type array, containing a single entry that is an object that contains a single field "name" that is of type array, that contains 2 objects. Object one contains a single key called "Senior" with fields name and country, and object 2, contains a single key "Junior" with fields name and country.

Hopefully this made sense and you now understand how JSON works.

EDIT: The OP has edited his post with valid json, so, this answer is no longer valid. Original was (as seen in the post edit history) :

string json = "people":{   "name":{ "Senior":{   "name": "Jan",  
"country": "US"   },   "Junior":{   "name": "George",   "country":
"CA"   }   }   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM