Home > Enterprise >  There is a problem parse to json my string value
There is a problem parse to json my string value

Time:12-06

{
    "wMetropolCardOrderID": 588,
    "success": true,
    "responseCode": 0,
    "responseMessage": "Kayıt Eklendi"
}

This json object returns from Postman.

my string value

As you see in the screenshot, I need to take wMetropolCardOrderID from the string value. I tried parsing json but got some errors. How can I get it correctly with using parsejson method. Also is there any way to take it except using substring method?

CodePudding user response:

You can parse the JSON and extract the field result.

using Newtonsoft.Json;

var json = resultnopbakye.Substring(resultnopbakye.IndexOf("{"));
int wMetropolCardOrderID = Convert.ToInt32(JObject.Parse(json)["wMetropolCardOrderID"]);

CodePudding user response:

It seems there is "more data" than just the JSON, at the beginning of your string you are also getting the date time and a <br />.

You can do the following

public class MyModel
{
    public int wMetropolCardOrderID {get;set;}  
    public bool success {get;set;}
    public int responseCode {get;set;}
    public string responseMessage {get;set;}

} 


string resultnopbakiyeJson = resultnopbakiye.split("<br />")[1];
// For Newtonsoft.Json
MyReturn myData = JsonConvert.DeserializeObject<MyModel>(resultnopbakiyeJson)
// For System.Text.Json
MyReturn myData = JsonSerializer.Deserialize<MyModel>(resultnopbakiyeJson);
 

It is also a good idea to add some defensive code, like checking if the string contains <br /> or checking if the split method returned an array larger than 1 prior accessing the index.

  • Related