Click here to Skip to main content
15,922,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have an issue to extract specific value of "WayBill"
I got error is "Accessed JArray values with invalid key value: "WayBill". Int32 array index expected."

Pls advice me

thank you

What I have tried:

JavaScript
Json is 
{
	"Status": true,
	"Message": "Shipment Creation Successful",
	"ResponseData": [{
		"PickupBranchCode": "DKPG",
		"DeliveryRouteCode": "HAKHG2M3",
		"WayBill": ["ZND167281208805"],
		"DeliveryHubCode": "HAKH",
		"DeliveryBranchCode": "HAKH",
		"PickupRouteCode": "DUSJW2WE",
		"PickupHubCode": "HSHM"
	}],
	"Reason": null
}

        Dim json = Me.txtJson.Text
        Dim obj As Object = JsonConvert.DeserializeObject(json)
Me.txtResult.Text = obj("ResponseData")("WayBill").ToString
Posted
Updated 4-Jan-23 18:13pm

1 solution

If you only want to strip out the WayBill Numbers, then you can use: Querying JSON with SelectToken - NewtownSoft[^]
C#
using Newtonsoft.Json.Linq;

string rawJson = 
    $$""" 
      {
      	"Status": true,
      	"Message": "Shipment Creation Successful",
      	"ResponseData": [{
      		"PickupBranchCode": "DKPG",
      		"DeliveryRouteCode": "HAKHG2M3",
      		"WayBill": ["ZND167281208805"],
      		"DeliveryHubCode": "HAKH",
      		"DeliveryBranchCode": "HAKH",
      		"PickupRouteCode": "DUSJW2WE",
      		"PickupHubCode": "HSHM"
      	}],
      	"Reason": null
      }
      """;

JObject jObj = JObject.Parse(rawJson);

IEnumerable<string> billNumbers = jObj
    .SelectToken("$.ResponseData[0]['WayBill']")
    .Values<string>();

string wayBillNumber = string.Join(", ", billNumbers);

Console.WriteLine($"WaBill #: {wayBillNumber}");

But if you want to deserialize the whole Json, then look at this article: Working with Newtonsoft.Json in C# & VB[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900