I have JSON data:
var decodedJson =
"{{
"user": {
"userId": "sid:C4F4E93856104F078A11FE95892F0158"
},
"authenticationToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmdWxscm93IjoiYWxsIiwiRGJnMiI6ImxvZ2luIiwidmVyIjoiMyIsInVpZCI6InNpZDpDNEY0RTkzODU2MTA0RjA3OEExMUZFOTU4OTJGMDE1OCIsImlzcyI6InVybjptaWNyb3NvZnQ6d2luZG93cy1henVyZTp6dW1vIiwiYXVkIjoidXJuOm1pY3Jvc29mdDp3aW5kb3dzLWF6dXJlOnp1bW8iLCJleHAiOjE0NDk3NTYzNzIsIm5iZiI6MTQ0NzE2NDM3Mn0.kc-0O_aorfTw9l9U6yY6wyVtQnckqNBJikBzxAcJZ_U"
}}";
Then I want to deserialize it dynamically using JSON.NET:
var result = JsonConvert.DeserializeObject<dynamic>(decodedJson);
Then I expect to extract the UserId and Token like this:
string userId = result.user.userId;
string userToken = result.authenticationToken;
But it is saying
"Unknown member user/ authenticationToken"
Any ideas?
UPDATED:
I have copied wrong json data, it actually should be like this:
{\"user\":{\"userId\":\"sid:C4F4E93856104F078A11FE95892F0158\"},\"authenticationToken\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmdWxscm93IjoiYWxsIiwiRGJnMiI6ImxvZ2luIiwidmVyIjoiMyIsInVpZCI6InNpZDpDNEY0RTkzODU2MTA0RjA3OEExMUZFOTU4OTJGMDE1OCIsImlzcyI6InVybjptaWNyb3NvZnQ6d2luZG93cy1henVyZTp6dW1vIiwiYXVkIjoidXJuOm1pY3Jvc29mdDp3aW5kb3dzLWF6dXJlOnp1bW8iLCJleHAiOjE0NDk3NjE1NDEsIm5iZiI6MTQ0NzE2OTU0MX0.oVH8R2134UQQDpXfzPv2mmrj7M05w2mzWtbp70i7GEU\"}
In the long run you would be better to copy the structure in the C# exactly. If your model changes for json then you will have to change your dynamic
code anyway and the bugs are easier to creep in.
The following classes can be used to parse your json after removing the extra {}
at the start and end of the response.
public class User
{
public string userId { get; set; }
}
public class RootObject
{
public User user { get; set; }
public string authenticationToken { get; set; }
}
You can utilise the following site to quickly map JSON to CSharp