1

I have JSON string in following format.

{
  "Request": {
    "Header": { "Action": "Login" },
    "DataPayload": {
      "UserName": "user",
      "Password": "password"
    }
  }
}

I need to deserialize the above JSON string without creating any Type or Anonymous type and I should be able to access properties like below in .NET.

Request.Header.Action : To get action value.
Request.DataPayload.UserName : To get username.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Harshanand Wankhede
  • 155
  • 2
  • 2
  • 11
  • 2
    Please don't just ask us to solve the problem for you. Show us how _you_ tried to solve the problem yourself, then show us _exactly_ what the result was, and tell us why you feel it didn't work. See "[What Have You Tried?](http://whathaveyoutried.com/)" for an excellent article that you _really need to read_. – John Saunders Jul 19 '14 at 19:31
  • you can deserialize it into a dictionary recursively, as described here: http://stackoverflow.com/questions/24781892/how-to-read-dynamic-returned-json-string-in-c/24782326#24782326 – tt_emrah Jul 19 '14 at 19:44
  • @tt_emrah, No need to manualy convert it to dictionary. JObject already implements `IDictionary`. – EZI Jul 19 '14 at 19:50
  • @EZI: oh, i missed that, sorry... however, i remember that they behave differently in case of key not found or null value. – tt_emrah Jul 19 '14 at 20:59

1 Answers1

3

You can do this easily using Json.NET.

Either parse your string as a JObject and use it like a dictionary:

var obj = JObject.Parse(str);
var action = obj["Request"]["Header"]["Action"];

Or deserialize it into a dynamic object, if you don't mind losing static typing:

dynamic obj = JsonConvert.DeserializeObject<dynamic>(str);
var action = obj.Request.Header.Action;
dcastro
  • 66,540
  • 21
  • 145
  • 155
  • 1
    dcastro, no need for ``. @HarshanandWankhede how many millions of times do you plan to do this operation to see the difference? – EZI Jul 19 '14 at 20:00
  • @HarshanandWankhede Premature optimization is the root of all evil. Factors like readability, flexibility and maintainability are much more important. For those reasons, I'd choose the first option. – dcastro Jul 19 '14 at 20:00