chadb768
chadb768

Reputation: 473

How to remove redundant encapsulating curly brackets from json?

I have a JSON object in C# that unfortunately is being returned like this:

var obj = 
{{
    answer: {
             one: "my answer one"
             two: "my answer two"
             }
}};

I want to be able to go like this:

string answerOne = obj.answer.one;

Since the outside curly brackets are present I am able to access my fields inside answer. How can I remove these or access the inside fields?

Upvotes: 2

Views: 10818

Answers (4)

vaibhav khairnar
vaibhav khairnar

Reputation: 103

it is a JObject.

JObject foo=JObject.parse(obj); //parse if it is string
var temp=(JObject)foo;
var answerone=temp["answer"]["one"]; //my answer one

Upvotes: 0

hxysayhi
hxysayhi

Reputation: 1987

It is not a valid Json.

Have a look at this.

If you have a string,look like this:

"{{
    answer: {
             one: "my answer one"
             two: "my answer two"
             }
}}"

you may replace "{{" and "}}" to "{" and "}",and then you can parse it.

Upvotes: 0

CBinet
CBinet

Reputation: 187

You could clean the string using the String.Replace method :

obj = obj.Replace("{{", "{"); // Replace the left curly braces
obj = obj.Replace("}}", "}"); // Replace the right curly braces

Upvotes: 2

Huan Jiang
Huan Jiang

Reputation: 257

This looks not a valid json string, I doubt any Json parser could deserialize it back to a object. If it happens to all API request, You'd better to ask your server developer to fix this bug. If you don't have control of that, You may need to write a HttpModule, to pre-process the Request.Body, sanify the data.

Upvotes: 0

Related Questions