1

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

Christoffer
  • 77
  • 1
  • 6
  • You can use `json.net` to deserialize the json string into an object (the easy way), or the classes in `Newtonsoft.Json.linq` to parse it manually. – Zohar Peled Dec 27 '18 at 13:54
  • You will have to de-serialize the string using a json parser such as json.net or javascriptserializer provided with .net framework. – shahkalpesh Dec 27 '18 at 13:55
  • That's not an array, it's an object. – ProgrammingLlama Dec 27 '18 at 14:06
  • A JSON string would have quotes around the names and values. Have you removed those quotes or are they not there? http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf This question covers answers regarding C# https://stackoverflow.com/q/6620165/125981 – Mark Schultheiss Dec 27 '18 at 14:07
  • Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Mark Schultheiss Dec 27 '18 at 14:14

2 Answers2

4

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"];
crellee
  • 855
  • 1
  • 9
  • 18
1

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
Rod Ramírez
  • 1,138
  • 11
  • 22