0

I am developing an application using ASP.NET MVC 4 and it involves web API call where the result I am getting for a specific record is a Json string. I am doing this web API call inside an action method of a controller and the result I am getting for such call is in the following form:

result = "{\"fname\":\"John\",\"lname\":\"Doe\",\"empno\":123456,\"dept\":\"IT\"}"

I am new to MVC and Json and would really appreciate any help on how I can extract specific values from this Json string such as the value for dept?

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
corix010
  • 551
  • 8
  • 25
  • Search for Restful JSON WCF client, you can use the same JSONSerializer and Deserializer and convert to POCO's. – SriN Dec 05 '12 at 16:48
  • Thanks for the quick reply. However, I am just trying to extract a specific value from the Json string and not trying to instantiate an object of a class from the Json string. In this example, I am just after the value of dept which is "IT". I wish I could do that with just a simple code like result["dept"]? – corix010 Dec 05 '12 at 16:56

1 Answers1

1

In order to use this as an actual object in your project you will need to deserialize this string. .NET has it's own deserialization or you can check out Json.Net which is pretty simple to figure out. Check out the documentation on JsonConvert.DeserializeObject<>...

ie...

Instructor desInst = new Instructor();
responseContent = rsp.Content.ReadAsStringAsync().Result;
desInst = JsonConvert.DeserializeObject<Instructor>(responseContent);
Brandon Clapp
  • 66,931
  • 6
  • 20
  • 24
  • I appreciate the quick response but I am just after a specific value in the Json string like in this example, the value of dept which is "IT". Do I really have to create a class for this? Is there a way where I could just do result["dept"] or something like that? Thanks. – corix010 Dec 05 '12 at 17:04
  • I'm somewhat new to the web api, myself. I have never done anything other than deserialize it into a poco, but it may be possible. I found this thread that may help (although it looks more complicated imo) http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net. I think you will still have to use Json.NET to deserialize though before you will be able to do anything with it. – Brandon Clapp Dec 05 '12 at 17:14
  • 1
    Thanks for the link. That really helped. I end up using the code: Dictionary values = JsonConvert.DeserializeObject>(json); – corix010 Dec 05 '12 at 17:39
  • Awesome, glad you got it figured out. – Brandon Clapp Dec 05 '12 at 17:40