简体   繁体   中英

Using a JSON array received as a string

I'm receiving a string, output , that looks like this:

{family_name:XXX, given_name:XXX, locale:en, name:XXX, picture:XXX, profile:XXX, sub:XXX}

I'd like to get some of these values and store them in variables, but since it's a string I cant use indexing (I would've just used var x = output[0] etc)

How would I get a hold of these values?

Thanks in advance

The structure of the string is a JSON-object. Therefore, you must handle it as a JSON-object. First parse it to JSON. eg. like this:

JObject json = JObject.Parse(YOUR_STRING);

And now to get the given value you wish, for instance family_name you can say:

string name = (string) json["family_name"];

I would recomend Json.Net.

Parse your string to json, and create a model that can hold those JSON values as

public class Person
{
    public string family_name {get;set}
    public string given_name {get;set;}
    public List<string> siblings{get;set;}
}

(This could be done with https://quicktype.io/csharp/ or manually)

Then:

string json = @"{
  'family_name': 'Foo',
  'given_name': 'Bar',
  'siblings': [
    'Jhon',
    'Doe'
  ]
}";

Person person = JsonConvert.Deserialize<Person>(json);

string familyName = person.family_name;
//Foo

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