Reputation: 108
Good day everyone, I'm trying to convert a string that looks like this:
"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"
If I do a quick inspection when the code is running, it looks like this:
After applying the following line of code:
var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);
It returns the object with two curly braces
{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
How can I avoid those two curly braces after converting the string to dynamic object?
I need to use it like this at the end:
var foo = Datos.Token.Value;
Thank you very much for your help.
Upvotes: 1
Views: 78
Reputation: 13060
The effects you're seeing (escaped quotes in the string and the braces) are just how the debugger has chosen to display those values.
"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"
is actually a string that contains
{"Estado":true,"Token":"3D16C8D8-058C-4FA7-AEA2-1A764A083B72","Nombre":"Agente COV"}
and
{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
Is how the debugger has chosen to display the dynamic object with 3 properties with values
The simplest way I'd tackle this would be to create a class for the JSON
public class MyObject{
public bool Estado { get; set; }
public Guid Token { get; set; }
public string Nombre { get; set; }
}
Then you can use Json.Net to deserialize it.
var json = "{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}";
var myObject = JsonConvert.DeserializeObject<MyObject>(json);
Then access the values like myObject.Token
etc.
Upvotes: 4
Reputation: 2133
You can first parse your json with
dynamic Datos = JObject.Parse(yourjson);
and retrieve the value by
var foo = Datos.Token
Note - JObject is from newtonsoft
Upvotes: 0