Home > Blockchain >  How can i fetch the element inside 2 {{}} in c #
How can i fetch the element inside 2 {{}} in c #

Time:02-11

var options = new RestClientOptions(Endpoint)
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject(responseContent);

the value in parsed is :

{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}

the value in requestContent :

"{
\"value1\" : \"input1\",
\"value2\" : null,
\"value3\" : {\"valuex\" : 4,
\"valuey\" : 5,
\"valuez\" : 6}
\"value4\" : 17
}"

I'm new to c#, all I want is to parse the data inside valuez which is 6 in this case, I tried so many things on request content like trying like deserializing and trying to parse the parsed value where I debugged and tried to access its child by putting . after parsed similar to what we'd do in javascript for example but nothing seems to be working.

CodePudding user response:

You need to DeserializeObject to an object of your type . example:

var parsed = JsonConvert.DeserializeObject<object>(responseContent);

or

public class MyClass
{
    public string value1 { get; set; }
    public string value2 { get; set; }
}
var parsed = JsonConvert.DeserializeObject<MyClass>(responseContent);

CodePudding user response:

You provided invalid JSON:

{
    "value1": "input1",
    "value2": null,
    "value3": {
        "valuex": 4,
        "valuey": 5,
        "valuez": 6
    }         // <---- missing comma here.
    "value4": 17
}

If unsure, you can always confirm if it's valid using a tool like JSONLint (remember to remove escape characters, which can be done using regex (online tool like regex101))

given you have a valid json (so just add the comma):

var r = JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(yourInputString);

... or as others mentioned, you can create a custom model. The easy way to do that is using another tool, i.e. Json2csharp. You can also refer to this article

  • Related