0

I have the following JSON Output:

{{
  "$type": "Asi.Soa.Core.DataContracts.PagedResult`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], Asi.Contracts",
  "Items": {
    "$type": "System.Collections.Generic.List`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], mscorlib",
    "$values": [
      {
        "$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
        "EntityTypeName": "14",
        "Properties": {
          "$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
          "$values": [
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "ResultRow",
              "Value": "1"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Work Phone",
              "Value": "(782) 438-7600"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Email",
              "Value": "[email protected]"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Full Name",
              "Value": "Agazny"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "iMISId",
              "Value": "eg1"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Preferred Phone",
              "Value": "780"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Organization",
              "Value": "Re"
            }
          ]
        }
      },
      {
        "$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
        "EntityTypeName": "14",
        "Properties": {
          "$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
          "$values": [
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "ResultRow",
              "Value": "2"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Work Phone",
              "Value": "7802"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Email",
              "Value": "aksm"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Full Name",
              "Value": "Aji"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "iMISId",
              "Value": "esa"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Preferred Phone",
              "Value": "780"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Organization",
              "Value": "Hom"
            }
          ]
        }
      }

I am trying to deserialize this response into workable c# objects and POST it to a different API that accepts a totally different format of JSON.

This is my code so far:

 using (var client = new HttpClient())
 {
      // Format headers
      client.DefaultRequestHeaders.Accept.Clear();

      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      // Request token, and append to headers
      await AddTokenToHeaders(client);

      // Query HTTP Service                
      var response = await client.GetAsync(baseUrl + "api/IQA?querydocumentversionkey=f2005a6e-7f47-47c3-a7e7-bbd2a7b6ab38");

      if (response.IsSuccessStatusCode)
      {
           var customer = await response.Content.ReadAsStringAsync();
           JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());

           JArray a = (JArray)result["Items"]["$values"][0]["Properties"];
           var test =  a.AsJEnumerable();

However, it's not picking up my entire JSON object and I am not able to map it to the properties of my class:

--Update.

I have updated my code and I was able to get the Jarray in the format I wanted, however when I try enumerate by jObject into my List of Class Customer, the properties I try to cast returns nulls.

Thanks for the response. I was able to get the output I was looking for by using the following code. However, attempting to put the output in my List of Customer class with the properties specified however, I am getting nulls on the properties of class Customer.

JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());
                JArray a = (JArray)result["Items"]["$values"];
                List<Customer> items = ((JArray)a).Select(x => new Customer
                {
                    ResultRow = (string)x["ResultRow"],
                    WorkPhone = (string)x["Work Phone"],
                    Email = (string)x["Email"],
                    FullName = (string)x["Full Name"],
                    iMISId = (string)x["iMISId"],
                    PreferredPhone = (string)x["Preferred Phone"],
                    Organization = (string)x["Organization"]
                }).ToList();


 public class Customer
    {
        [JsonProperty("ResultRow")]
        public string ResultRow { get; set; }

        [JsonProperty("Work Phone")]
        public string WorkPhone { get; set; }

        [JsonProperty("Email")]
        public string Email { get; set; }

        [JsonProperty("Full Name")]
        public string FullName { get; set; }

        [JsonProperty("iMISId")]
        public string iMISId { get; set; }

        [JsonProperty("Preferred Phone")]
        public string PreferredPhone { get; set; }

        [JsonProperty("Organization")]
        public string Organization { get; set; }

    }
3
  • 1
    What do you mean by "it's not picking up my entire JSON object"? Commented Aug 8, 2018 at 22:13
  • BTW, do not dispose HttpClient. Commented Aug 8, 2018 at 23:00
  • Parsing is not the same as deserializing Commented Aug 8, 2018 at 23:16

1 Answer 1

1

There is a mistake in the code you provided. You are trying to cast the Properties into a JArray when it is an object.

If you do want the array in the Properties object, do this:

JArray arr = (JArray)result["Items"]["$values"][0]["Properties"]["$values"];

Otherwise, if you are looking for the Properties object, then you should do this instead:

JObject obj = (JObject)result["Items"]["$values"][0]["Properties"];

Finally, to rebuild the list of Customer instances, you could use the following logic with the static methods:

var customersJson = (JArray)result["Items"]["$values"];

var customers = new List<Customer>();

foreach (JObject o in customersJson)
{
     var customerJson = (JArray) o["Properties"]["$values"];
     customers.Add(BuildCustomer(customerJson));
}

[...]

private static Customer BuildCustomer(JArray a)
{
    return new Customer
    {
        ResultRow = GetValue(a, "ResultRow"),
        WorkPhone = GetValue(a, "Work Phone"),
        Email = GetValue(a, "Email"),
        FullName = GetValue(a, "Full Name"),
        iMISId = GetValue(a, "iMISId"),
        PreferredPhone = GetValue(a, "Preferred Phone"),
        Organization = GetValue(a, "Organization")
     };
}

private static string GetValue(JArray array, string name)
{
    JToken obj = array.FirstOrDefault(x => (string) x["Name"] == name);

    if (obj == null)
        return string.Empty;

    return (string) obj["Value"];
}
Sign up to request clarification or add additional context in comments.

4 Comments

I've edited my original comment and added the changes I've made to my code and where I'm stuck now
@Junior I have edited my answer to include the deserialization of a Customer out of a JArray. If it does answer your question, please mark it as an answer so that it can help someone else.
Thanks this works, but it only builds a single customer. I want to deseriliaze the entire response using: JArray a = (JArray)result["Items"]["$values"] This will return many Customer records. I want to store this in a c# collection. I thought the JArray function does that, but it does not.
thank you so much. This was exactly what I was looking for. Syntax for the foreach loop is perfect! Thanks again

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.