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.

4
  • 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?" for an excellent article that you really need to read. Commented Jul 19, 2014 at 19:31
  • you can deserialize it into a dictionary recursively, as described here: stackoverflow.com/questions/24781892/… Commented Jul 19, 2014 at 19:44
  • @tt_emrah, No need to manualy convert it to dictionary. JObject already implements IDictionary. Commented Jul 19, 2014 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. Commented Jul 19, 2014 at 20:59

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

dcastro, no need for <dynamic>. @HarshanandWankhede how many millions of times do you plan to do this operation to see the difference?
@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.

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.