nun3z
nun3z

Reputation: 108

How to convert a string (json with scape chars) to dynamic object?

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:

enter image description here

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"}}

enter image description here

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

Answers (2)

phuzi
phuzi

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

  • Estado - true
  • Token - "3D16C8D8-058C-4FA7-AEA2-1A764A083B72"
  • Nombre - "Agente COV"

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

Prany
Prany

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

Related Questions