0

I am new to c# , but i have a lot of experience when using OOP like PHP and Java. I have a HTTP web response in my c# code which returns a JSON object, i read many articles online and i saw some of microsoft's documentation regarding the JSON decode and other method, however , i used PHP before and i know that there is a very simple way to do it like this:

considering that $response is the response from the web service:

$json_string = json_decode($response,true);
$var = $json_string["test"]["country"];

i saw a similar question on the site and it had an answer:

dynamic response = JsonConvert.DeserializeObject(json);

Console.WriteLine("PropName:" +     response.data[1].attachment.properties[0].name);

foreach (var data in response.data)
{
    if (data.attachment != null)
    Console.WriteLine((string)data.attachment.name);
}

As you can see here a dynamic object was created to get the son object (string)data.attachment.name, so the value name is fixed,i was wondering if this value can be a string like so:

String 1="attachement";
String 2="name";
(string)responsedata.1.2;

I know the syntax is wrong and that 1 and 2 should be of type dynamic. Can those vapes be strings like the case of the php example i gave in the beginning of my question.

is there a similar and easy code in c# that has the same output and it is easy to use? Appreciate your help.

Walid
  • 71
  • 1
  • 10
  • 1
    Maybe this is what you are looking for? http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – Maximus2012 Oct 14 '16 at 21:24

1 Answers1

0

You can use newtonsoft for desrializing json object.

string json = @"{
   'Country': 'US',
   'State': IL,
   'CreatedDate': '2016-10-14T00:00:00Z'       
 }";

DefineYourObject obj = JsonConvert.DeserializeObject<DefineYourObject>(json);    
Console.WriteLine(obj.Country);
Ratan
  • 863
  • 5
  • 12
  • 28