简体   繁体   中英

Reading JSON string in C#

I have data in JSON file format like

{
   "default":{
    "name":"username",
    "school":"school_name"
    },
    
    "type1":{
    "name":"studentname",
    "school":"schoolName"
    },
    
    "type2":{
    "name":"user_name",
    "school":"schooltitle"
    }
}

I am reading data using

Dictionary<string,string> values = JsonConvert.DeserializeObject< Dictionary<string,string> >( json )

where json is a text from json file. I want to access specific code block like if student is of type 1 then check if that type exist and access that block otherwise access default block. How to do it? I want inner block values as key value pair

If we fix the Json with the missing , you should be able to Deserialize it to Dictionary<string, Dictionary<string, string>> :

var innerData = new Dictionary<string, string>{
    {"name", "username"}, 
    {"school", "school_name"}
};
var data = new Dictionary<string, Dictionary<string, string>>{
    {"default", innerData}, 
    {"type1", innerData}, 
    {"type2", innerData}, 
};      

string inputJson = JsonConvert.SerializeObject(data);

Note that the generated Json match yours:

{
 "default":{"name":"username", "school":"school_name"}
 , "type1":{"name":"username", "school":"school_name"}
 , "type2":{"name":"username", "school":"school_name"}
}

And the deseralization:

var result = JsonConvert.DeserializeObject< Dictionary<string, Dictionary<string, string>> >(inputJson);

var type1Element = result["type1"];
foreach(var keyValue in type1Element){
    Console.WriteLine("{keyValue.Key} => {keyValue.Value}");

}

online Demo .

I hope the below code will work. (Though, I haven't tested it)

JObject jsonObject = (JObject)JsonConvert.DeserializeObject(your_json);
string selectedBlock;
string to_check = "type1"; // I have hardcoded this for example

try
{ 
if((string)jsonObject.SelectToken(to_check)!=null)
selectedBlock = (string)jsonObject.SelectToken(to_check);
else
selectedBlock = (string)jsonObject.SelectToken("default");
}
catch (Exception e)
{
throw e;
}

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