Reputation: 215
My JSON string is:
string b = "\"{\"Response\":[{\"ResponseCode\":\"0\",\"ResponseMessage\":\"71a88836-57f0-4b0e-a59c-071ea6d6f1de\"}]}\"";
I want to retrieve value of ResponseCode
and ResponseMessage
.
When I tried something like this to parse my JSON string
var userObj = JObject.Parse(b);
I am getting Error such as:
Newtonsoft.Json.JsonReaderException
: 'Error readingJObject
fromJsonReader
. CurrentJsonReader
item is not an object:String
. Path '', line 1, position 3.'
Please help me to retrieve ResponseCode
And ResponseMessage
from the given string.
Upvotes: 1
Views: 196
Reputation: 3576
You need to trim the outer doublequotes, otherwise it is not a valid json format
var userObj = JObject.Parse(b.Trim('"'));
Then you can retrieve the data either by declaring a class matching the json format and deserializing it, or just accessing the properties dynamically
var response = (JArray)userObj["Response"];
string responseCode = response[0]["ResponseCode"].Value<string>();
string responseMessage = response[0]["ResponseMessage"].Value<string>();
Upvotes: 4
Reputation: 76
You should use create a class that matches the properties you expect. I think you want a Response-class with property ResponseCode and ResponseMessage.
If that's the case, you should remove the outer "Response" tag. Also the backslash should be removed and the double quotes should be replaced by single quotes.
Try this:
class Response
{
public string ResponseCode { get; set; }
public string ResponseMessage { get; set; }
}
static void Main(string[] args)
{
string body = @"{'ResponseCode':0,'ResponseMessage':'71a88836-57f0-4b0e-a59c-071ea6d6f1de'}";
var response = JsonConvert.DeserializeObject<Response>(body );
}
Upvotes: 0