4

I have written these lines of code which make an API request and in return I get valid JSON response:

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(_apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsAsync<ExpandoObject>();
                    return Json(data);
                }

            }

The data looks like below:

enter image description here

Is it possible to get the value of ProductID and Price. I want to assign them to something like:

int productId = ...
int price = ...

How can i do this using C#?

etrupja
  • 2,710
  • 6
  • 22
  • 37

4 Answers4

4

.Net 4.0 supports creating dynamic objects directly from json:

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
dynamic item = serializer.Deserialize<object>("{ \"productId\":\"124889\" }");
string test= item["productId"];

If your using Json.NET or Newtonsoft.Json.Linq - this answer should help you.

Json.Net

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Newtonsoft.Json.Linq

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

string name = stuff.Name;
string address = stuff.Address.City;
Community
  • 1
  • 1
A G
  • 21,087
  • 11
  • 87
  • 112
3

Check out the Newtonsoft Json nuget package. Basically, you create an model with the variables you need, then you call the deserialize method from Newtonsoft. Here's some pseudo code

public class MyObject
{ 
    int ProductID { get; set; }
    int Price { get; set; }
    int Systems { get; set; }    
}

Then in your method:

using Newtonsoft.Json;

public class MyMethod(string json)
{
     MyObject obj = JsonConvert.DeserializeObject<MyObject>(json);
}

Something like that.

gev125
  • 152
  • 3
  • 9
3

I am sorry to answer to my own question but I just found the solution and i wanted to post here: You need to add these lines of code after data

var _dataResponse = JToken.Parse(JsonConvert.SerializeObject(data));
var _dataResponseProductID = _dataResponse["ProductID"];
var _dataResponsePrice = _dataResponse["Price"];

After that the values taken can be converted to desired data types.

etrupja
  • 2,710
  • 6
  • 22
  • 37
2

Create an object and Deserialize the json object.

http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_jsonconvert.htm

tssutha
  • 99
  • 8