Anthony
Anthony

Reputation: 19

How to read Json Response from a web service

I am trying to get the individual fields of the JSON response from this method and save to a variable.

  var responseData = MyClient.UploadString(VendConfig.PURCHASEURL, "POST", allData);
  Utility.WriteLog(responseData, _hostingEnvironment);

This is the response I get when I call the above service.

{
  "result_code": 0,
  "result": {
    "total_paid": 1000,
    "total_unit": 35.5,
    "token": "2344,
    "customer_number": "0001",
    "customer_name": "Test",
    "meter_number": "4700087",
    "gen_datetime": "2020/2/25 16:00:06",
    "gen_user": "WED2",
    "company": "MyCompany",
    "price": 26.83,
    "vat": 5,
    "tid_datetime": "2020/2/25 16:01:06",
    "currency": "NGN",
    "unit": "kWh",
    "TaskNo": "343"
  },
  "reason": "OK"
}

What I want is to save each of these fields into a variable. Below is what I have already tried

var jsonMatch = Regex.Match(responseData, @"\((?<json>.*)\)");
var json = jsonMatch.Groups["json"].Value;
var token = JToken.Parse(json);
var result_code = token["result_code"].Value<string>();
string [] result = token["result"].Value<string[]>();
var reason  = token["reason"].Value<string>();

However I get the following exception when I try the above

Message = "Error reading JToken from JsonReader. Path '', line 0, position 0."

Upvotes: 0

Views: 1227

Answers (1)

sam
sam

Reputation: 1985

You can use Json libraries to make this job easier. For example, you can use Newtonsoft Json.

  1. Add Newtonsoft Json package to your project.
  2. Define classes to simulate your response structure as shown below:
  3. Use DeserializeObject of Newtonsoft json to deserialize the json to the objects of classes that you just defined in step 2.
public class ResponseData
{
  public int result_code {get; set;}
  public Result result {get; set;}
  public string reason {get; set;}
}

public class Result
{
  public int total_paid {get; set;}
  public float total_unit {get; set;}

  // if you want to override the json response property names with your own names, then you could use JsonProperty as shown below:
    [JsonProperty("customer_number")]
  public string CustomerNumber {get; set;}
  public string customer_name {get; set;}
  // Ohter properties go here 
}
var responseData = MyClient.UploadString(VendConfig.PURCHASEURL, "POST", allData);
                Utility.WriteLog(responseData, _hostingEnvironment);
var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseData>(responseData);
// After this, you can access properties via responseObject.result_code, responseObject.reason and responseObject.result etc

Upvotes: 4

Related Questions