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

5
  • 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. Commented Dec 27, 2018 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. Commented Dec 27, 2018 at 13:55
  • That's not an array, it's an object. Commented Dec 27, 2018 at 14:06
  • A JSON string would have quotes around the names and values. Have you removed those quotes or are they not there? ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf This question covers answers regarding C# stackoverflow.com/q/6620165/125981 Commented Dec 27, 2018 at 14:07
  • Possible duplicate of Deserialize JSON into C# dynamic object? Commented Dec 27, 2018 at 14:14

2 Answers 2

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"];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.