0

I am working with an azure mobile app and it returns json data with a format I cannot read. The sting is acquired using

var newMember = new Member() { Id = Settings.UserId };
var url = azureService.Client.MobileAppUri + ".auth/me";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-ZUMO-AUTH", Settings.AuthToken);
var response = await client.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode();
dynamic responseBody = await response.Content.ReadAsStringAsync();

responseBody is

"[
  {
    \"id_token\": \"tokenstring\",
    \"provider_name\": \"aad\",
    \"user_claims\": [
      {
        \"typ\": \"exp\",
        \"val\": \"903i4231\"
      },
      {
        \"typ\": \"nbf\",
        \"val\": \"123516345294\"
      },
      {
        \"typ\": \"ver\",
        \"val\": \"1.0\"
      },
      {
        \"typ\": \"iss\",
        \"val\": \"https: \\\/\\\/login.microsoftonline.com\\\/somestring\\\/v2.0\\\/\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/nameidentifier\",
        \"val\": \"someotherstring\"
      },
      {
        \"typ\": \"aud\",
        \"val\": \"anotherstringstill\"
      },
      {
        \"typ\": \"nonce\",
        \"val\": \"stringy\"
      },
      {
        \"typ\": \"iat\",
        \"val\": \"3543345\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/ws\\\/2008\\\/06\\\/identity\\\/claims\\\/authenticationinstant\",
        \"val\": \"6363456345\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/givenname\",
        \"val\": \"FIRSTNAME?\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/surname\",
        \"val\": \"LastName?\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/identity\\\/claims\\\/identityprovider\",
        \"val\": \"google.com\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/identity\\\/claims\\\/objectidentifier\",
        \"val\": \"somestringelse\"
      },
      {
        \"typ\": \"emails\",
        \"val\": \"address@gmail.com\"
      },
      {
        \"typ\": \"tfp\",
        \"val\": \"B2C_1_ScoreSignupIn\"
      }
    ],
    \"user_id\": \"useridstring\"
  }
]"

How can I convert this to a useful C# object so I can get the string Firstname? and LASTNAME?

I tried

string firstName = responseJson.claims.givenname;

to no avail. Also, what is this type of JSON called. I remember reading about it while learning about azure API but I cannot remember where. I don't even know what to call it to search it up. Also the json prettyprints at jsonprettyprint.com but I cannot convert it to a C# object using http://json2csharp.com/

Mohit S
  • 13,723
  • 6
  • 34
  • 69
xerotolerant
  • 1,955
  • 4
  • 21
  • 39
  • The actual message is valid json I changed the values in there since it is filled with tokens all over the place that I am removed. I'll try to edit it again so the json is valid. – xerotolerant Dec 14 '16 at 06:17
  • You are not able to convert to parse this json and convert it object, Right? – Saadi Dec 14 '16 at 06:31
  • This specific object got mangled when I tried to remove private data from it. However the compiler does not complain when parsing the response from the server. I just don't understand how to get the data out of the object. – xerotolerant Dec 14 '16 at 06:33
  • Use Newtonsoft Nuget package and try the way that @Mohit posted as an answer. – Saadi Dec 14 '16 at 06:37
  • That worked thanks. I still don't understand the formatting for this json. are all of the `/` escape characters or something? – xerotolerant Dec 14 '16 at 06:49

2 Answers2

3

You can Install-Package Newtonsoft.Json and then this is what you can do to find the values from the JSON

string jsn = File.ReadAllText("YourJSON.txt");
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(jsn);
foreach(UserClaim uc in ro[0].user_claims)
{
    if(uc.val=="FIRSTNAME")
    {
        //Do whatever you want.
    }
    //or
    if(uc.typ.Contains("givenname"))
    {
        Console.WriteLine(uc.val);
    }


}

This will be the classes for your JSON

public class UserClaim
{
    public string typ { get; set; }
    public string val { get; set; }
}

public class RootObject
{
    public string id_token { get; set; }
    public string provider_name { get; set; }
    public List<UserClaim> user_claims { get; set; }
    public string user_id { get; set; }
}
Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

Please try this

JavaScriptSerializer serializer = new JavaScriptSerializer(); 

dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");

string test= item["test"];

Replace this

"{ \"test\":\"some data\" }"

with your JSON string.

You can also specify the exact data type instead of object and dynamic variables.

maulik sakhare
  • 1,957
  • 1
  • 12
  • 19
  • Even though Mohit's solution worked I want ot try your suggestion to understand this better. By doing your recommendation is it possible to get the value of such a complicated object without looping? – xerotolerant Dec 14 '16 at 06:53
  • That produced the error `System.ArgumentException: Accessed JArray values with invalid key value: "user_claims". Array position index expected.` I used `JsonConvert.DeserializeObject()` Since I could not find an object by the name JavascriptSerializer. – xerotolerant Dec 14 '16 at 07:03
  • I just meant that U should try to write "List ro = JsonConvert.DeserializeObject>(jsn);" write "RootObject" instead of dynamic and List instead of object. – maulik sakhare Dec 14 '16 at 07:05
  • This line is same as mohit has mentioned. :) – maulik sakhare Dec 14 '16 at 07:06
  • Oh ok. ``System.Collections.Generic.List.this[int]' has some invalid arguments` is the result this time. Are you sure you aren't thinking of Javascript for that last bit? I know you can accesss object properties using array notation in JS but it doesn't seem to be working C#. – xerotolerant Dec 14 '16 at 07:10
  • Let me provide you the exact syntax i.e List item = serializer.Deserialize>(YouJsonString); You will get the list of object's in item and You can iterate it to get the required Output – maulik sakhare Dec 14 '16 at 07:30
  • That's what I did. `string test= item["test"];` seems to be the problem. Specifically the use of a string in the `[]`rather than and int. – xerotolerant Dec 14 '16 at 07:33
  • No. I think you misunderstood what I told. If you specify the type instead of object and dynamic keyword. You will get an object of that type.In our case we will write `List items = serializer.Deserialize>(YouJsonString);` so we will get list of RootObject as an output. So to get the value we need to iterate this list. You cannot get values by `string test= item["test"]`. To get value You can do as `foreach(var item in items) { var tk = item.id_token; var claims = item.user_claims; foreach(var claim in user_claims){ var typ = claim.typ; } }` – maulik sakhare Dec 14 '16 at 14:37
  • Oh ok thanks for your patience and information. It is possible to do test = item["test"] in JavaScript. So I though you meant that that would also work somehow in C # as well. – xerotolerant Dec 14 '16 at 14:42
  • No problem friend :) – maulik sakhare Dec 14 '16 at 14:43