Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

How to get some values from a JSON string in C#?

I have a string and I want to get some values from it.

My strings seem like:

string1:

"{
   "id": "100000280905615",
 
 "name": "Jerard Jones",
 
   "first_name": "Jerard",
 
   "last_name": "Jones",
 
   "link": "https://www.facebook.com/Jerard.Jones",
 
   "username": "Jerard.Jones",
 
   "gender": "female",
 
   "locale": "en_US"
}"

string2:

"{
   "id": "100000390001929",
  
   "name": "\u05d1\u05d2\u05e8\u15dc\u25d9 \u05d1\u05e8\u05d5\u05e9",
  
   "first_name": "\u05d4\u05d2\u05e7\u02dc\u05d9",
  
   "last_name": "\u05d1\u05e8\u05d5\u05e9",
  
   "link": "https://www.facebook.com/people/\u05d2\u05d1\u05e@\u05dc\u05d9-\u05d1\u05e8\u05d4\u05e9/100000390001929",
  
   "gender": "female",
  
   "locale": "he_IL"
}"

Unfortunately, there is a situation that a string will be by the same concept, but without some parameters:

string3:

"{
   "id": "100000390001929",
  
   "last_name": "\u05d1\u05e8\u05d5\u05e9",
  
   "gender": "female",
  
   "locale": "he_IL"
}"

How can I get the values of: id, first_name, last_name, gender, locale?

Any help appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{
   "id": "100000280905615", 
 "name": "Jerard Jones",  
   "first_name": "Jerard", 
   "last_name": "Jones", 
   "link": "https://www.facebook.com/Jerard.Jones", 
   "username": "Jerard.Jones", 
   "gender": "female", 
   "locale": "en_US"
}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...