Yukwong Tsang Yukwong Tsang - 1 year ago 101
JSON Question

Get API Return JSON Payload in C#

I created a Web API and it needs to read the response in header with json content, therefore I use code below:

HttpRequestMessage re = Request;
var payLoadJson = re.Content;
string jsonContent = payLoadJson.ReadAsStringAsync().Result;
var test = JObject.Parse(jsonContent);

And here is the response of
var test

"pushToken": "AAABBBCCC"

Can any body tell me how to get the value of

always get null because of double braces.

Jim Jim
Answer Source

Your string in valid Json format:

    "pushToken": "AAABBBCCC"

Getting the payload

var pushToken = JObject.Parse(json)["pushToken"];

(Also note that pushtoken is between double quotes not single quotes as per your example, you should get an error with singles once)


dynamic obj = JsonConvert.DeserializeObject(json);

var pushToken = obj.pushToken;

As a side note:

In case you receive that bad invalid Json like you described ... I would actually have no idea how that's even possible. Then remove the two braces before parsing or deserializing.

json = json.Trim();
json = json.Substring(1, json.Length - 2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download