Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have issue in
Newtonsoft.Json.JsonSerializationException

Once use the external api url, error prompt
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.



Pls advice me.
Thank you
Maideen

What I have tried:

Public Class BouncesAndBlocks
        Public Property status As String
        Public Property message As String
        Public Property data As IEnumerable(Of Data)


    End Class
    Public Class Data
        Public Property sname As String
        Public Property saddress1 As String
        Public Property saddress2 As String
        Public Property scity As String
        Public Property spostcode As String
        Public Property sstate As String
        Public Property dairport As String
        Public Property scountry As String
        Public Property detailOfContent As String
        Public Property weight As String
        Public Property productPackages As String
        Public Property dimensionX As String
        Public Property dimensionY As String
        Public Property dimensionZ As String
        Public Property chargeableRate As String
        Public Property rname As String
        Public Property rphone As String
        Public Property raddress1 As String
        Public Property raddress2 As String
        Public Property rpostcode As String
        Public Property rcity As String
        Public Property rstate As String
        Public Property rairport As String
        Public Property rcountry As String
        Public Property rremark As String
        Public Property rvia As String
        Public Property serviceModeId As String
        Public Property agentId As String
        Public Property trackingNo As String


    End Class
    Private Sub POST_TEST_DATA()
        Dim url = New RestClient("http://avalon.insignianetworks.cloud/srcargo/rest/getBookingList")
        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
        url.Timeout = -1

        'Dim request = New RestRequest(Method.POST)
        Dim request = New RestRequest(Method.GET)

        request.AddHeader("Authorization", "Bearer 123|ABC123")
        Dim response As IRestResponse = url.Execute(request)
        Dim json As String = response.Content
        Dim res As BouncesAndBlocks = JsonConvert.DeserializeObject(Of BouncesAndBlocks)(json)  '' original
        For Each bouncesAndBlock In res.data


            Try
                Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectString").ConnectionString
                Dim query As String = "INSERT INTO Red_X_temp " &
                                          "(sname, saddress1, saddress2, scity, spostcode, sstate," &
                                          "dairport, scountry, detailOfContent, weight, productPackages, " &
                                          "dimensionX, dimensionY, dimensionZ, chargeableRate, rname, rphone, " &
                                          "raddress1, raddress2, rpostcode, rcity, rstate, rairport, rcountry, " &
                                          "rremark, rvia, serviceModeId, agentId, trackingno)" &
                                       "VALUES" &
                                          "(@sname, @saddress1, @saddress2, @scity, @spostcode, @sstate," &
                                          "@dairport, @scountry, @detailOfContent, @weight, @productPackages, " &
                                          "@dimensionX, @dimensionY, @dimensionZ, @chargeableRate, @rname, @rphone, " &
                                          "@raddress1, @raddress2, @rpostcode, @rcity, @rstate, @rairport, @rcountry, " &
                                          "@rremark, @rvia, @serviceModeId, @agentId, @trackingno)"

                Using con As SqlConnection = New SqlConnection(conString)
                    Dim cmd As SqlCommand = New SqlCommand(query, con)

                    cmd.Parameters.AddWithValue("@sname", bouncesAndBlock.sname)
                    cmd.Parameters.AddWithValue("@saddress1", bouncesAndBlock.saddress1)
                    cmd.Parameters.AddWithValue("@saddress2", bouncesAndBlock.saddress2)
                    cmd.Parameters.AddWithValue("@scity", bouncesAndBlock.scity)
                    cmd.Parameters.AddWithValue("@spostcode", bouncesAndBlock.spostcode)
                    cmd.Parameters.AddWithValue("@sstate", bouncesAndBlock.sstate)
                    cmd.Parameters.AddWithValue("@dairport", bouncesAndBlock.dairport)
                    cmd.Parameters.AddWithValue("@scountry", bouncesAndBlock.scountry)
                    cmd.Parameters.AddWithValue("@detailOfContent", bouncesAndBlock.detailOfContent)
                    cmd.Parameters.AddWithValue("@weight", bouncesAndBlock.weight)
                    cmd.Parameters.AddWithValue("@productPackages", bouncesAndBlock.productPackages)
                    cmd.Parameters.AddWithValue("@dimensionX", bouncesAndBlock.dimensionX)
                    cmd.Parameters.AddWithValue("@dimensionY", bouncesAndBlock.dimensionY)
                    cmd.Parameters.AddWithValue("@dimensionZ", bouncesAndBlock.dimensionZ)
                    cmd.Parameters.AddWithValue("@chargeableRate", bouncesAndBlock.chargeableRate)
                    cmd.Parameters.AddWithValue("@rname", bouncesAndBlock.rname)
                    cmd.Parameters.AddWithValue("@rphone", bouncesAndBlock.rphone)
                    cmd.Parameters.AddWithValue("@raddress1", bouncesAndBlock.raddress1)
                    cmd.Parameters.AddWithValue("@raddress2", bouncesAndBlock.raddress2)
                    cmd.Parameters.AddWithValue("@rpostcode", bouncesAndBlock.rpostcode)
                    cmd.Parameters.AddWithValue("@rcity", bouncesAndBlock.rcity)
                    cmd.Parameters.AddWithValue("@rstate", bouncesAndBlock.rstate)
                    cmd.Parameters.AddWithValue("@rairport", bouncesAndBlock.rairport)
                    cmd.Parameters.AddWithValue("@rcountry", bouncesAndBlock.rcountry)
                    cmd.Parameters.AddWithValue("@rremark", bouncesAndBlock.rremark)
                    cmd.Parameters.AddWithValue("@rvia", bouncesAndBlock.rvia)
                    cmd.Parameters.AddWithValue("@serviceModeId", bouncesAndBlock.serviceModeId)
                    cmd.Parameters.AddWithValue("@agentId", bouncesAndBlock.agentId)
                    cmd.Parameters.AddWithValue("@trackingno", bouncesAndBlock.trackingNo)
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using

                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "alert('Record Saved !');", True)
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "alert('Record wrong !');", True)
            End Try
        Next

    End Sub


I have debugged, I have got below Json which is from external API url.

this is that

[
	{	
		""id"":120,
		""trackingNo"":""683123690493"",
		""sname"":""AMAN SALES SDN BHD"",
		""sphone"":""019-8824500"",
		""saddress1"":""NO 39/39A,JALAN 23 TAMAN"",
		""saddress2"":""BUKIT KUCHAI"",
		""scity"":""PUCHONG"",
		""spostcode"":""47100"",
		""sstate"":""Selangor"",
		""dairport"":""KUL"",
		""scountry"":""MY"",
		""detailOfContent"":""PARTS"",
		""weight"":5.0,
		""productPackages"":1,
		""dimensionX"":40.0,
		""dimensionY"":28.0,
		""dimensionZ"":26.0,
		""chargebleRate"":5.0,
		""rname"":""AMAN SALES & SERVICES (M) SDN BHD"",
		""rphone"":""089-880757"",
		""raddress1"":""LOT13 NEW KIMBELL INDUSTRIAL"",
		""raddress2"":""ESTATE,MDLD 4974,JALAN KIMBELL 91100"",
		""rpostcode"":""91100"",
		""rcity"":""LAHAD DATU"",
		""rstate"":""Sabah"",
		""rairport"":""LDU"",
		""rcountry"":""MY"",
        ""rremark"":""PLEASE DEL  ASAP"",
		""rvia"":""BKI"",
		""serviceModeId"":null,
		""agentId"":null"
	}
]
Posted
Updated 30-Oct-22 18:01pm
v2
Comments
Graeme_Grant 31-Oct-22 0:00am    
Never post your Bearer Token or any API secrets in a public forum. I strongly recommend invalidating your credentials and getting new ones.

1 solution

A couple of things:
1. Invalid double quotes:
""id"":120,

2. Invalid end quote:
""agentId"":null"

3. Array of objects with only one object:
[{

}]


Once you can get valid Json data (use: JSON Online Validator and Formatter - JSON Lint[^] ). Your Json should be:
JavaScript
[
	{	
		"id":120,
		"trackingNo":"683123690493",
		"sname":"AMAN SALES SDN BHD",
		"sphone":"019-8824500",
		"saddress1":"NO 39/39A,JALAN 23 TAMAN",
		"saddress2":"BUKIT KUCHAI",
		"scity":"PUCHONG",
		"spostcode":"47100",
		"sstate":"Selangor",
		"dairport":"KUL",
		"scountry":"MY",
		"detailOfContent":"PARTS",
		"weight":5.0,
		"productPackages":1,
		"dimensionX":40.0,
		"dimensionY":28.0,
		"dimensionZ":26.0,
		"chargebleRate":5.0,
		"rname":"AMAN SALES & SERVICES (M) SDN BHD",
		"rphone":"089-880757",
		"raddress1":"LOT13 NEW KIMBELL INDUSTRIAL",
		"raddress2":"ESTATE,MDLD 4974,JALAN KIMBELL 91100",
		"rpostcode":"91100",
		"rcity":"LAHAD DATU",
		"rstate":"Sabah",
		"rairport":"LDU",
		"rcountry":"MY",
        "rremark":"PLEASE DEL  ASAP",
		"rvia":"BKI",
		"serviceModeId":null,
		"agentId":null
	}
]

You can then generate classes for the data with tools like: JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^]
C#
public class Response
{

	[JsonProperty("id")]
	public int Id { get; set; }

	[JsonProperty("trackingNo")]
	public string TrackingNo { get; set; }

	[JsonProperty("sname")]
	public string Sname { get; set; }

	[JsonProperty("sphone")]
	public string Sphone { get; set; }

	[JsonProperty("saddress1")]
	public string Saddress1 { get; set; }

	[JsonProperty("saddress2")]
	public string Saddress2 { get; set; }

	[JsonProperty("scity")]
	public string Scity { get; set; }

	[JsonProperty("spostcode")]
	public string Spostcode { get; set; }

	[JsonProperty("sstate")]
	public string Sstate { get; set; }

	[JsonProperty("dairport")]
	public string Dairport { get; set; }

	[JsonProperty("scountry")]
	public string Scountry { get; set; }

	[JsonProperty("detailOfContent")]
	public string DetailOfContent { get; set; }

	[JsonProperty("weight")]
	public double Weight { get; set; }

	[JsonProperty("productPackages")]
	public int ProductPackages { get; set; }

	[JsonProperty("dimensionX")]
	public double DimensionX { get; set; }

	[JsonProperty("dimensionY")]
	public double DimensionY { get; set; }

	[JsonProperty("dimensionZ")]
	public double DimensionZ { get; set; }

	[JsonProperty("chargebleRate")]
	public double ChargebleRate { get; set; }

	[JsonProperty("rname")]
	public string Rname { get; set; }

	[JsonProperty("rphone")]
	public string Rphone { get; set; }

	[JsonProperty("raddress1")]
	public string Raddress1 { get; set; }

	[JsonProperty("raddress2")]
	public string Raddress2 { get; set; }

	[JsonProperty("rpostcode")]
	public string Rpostcode { get; set; }

	[JsonProperty("rcity")]
	public string Rcity { get; set; }

	[JsonProperty("rstate")]
	public string Rstate { get; set; }

	[JsonProperty("rairport")]
	public string Rairport { get; set; }

	[JsonProperty("rcountry")]
	public string Rcountry { get; set; }

	[JsonProperty("rremark")]
	public string Rremark { get; set; }

	[JsonProperty("rvia")]
	public string Rvia { get; set; }

	[JsonProperty("serviceModeId")]
	public object ServiceModeId { get; set; }

	[JsonProperty("agentId")]
	public object AgentId { get; set; }
}

You need to understand Json syntax to correctly deserialize. As pointed out above, you have a list of objects [{ ... }] however there is only one object in the respose.

Now you can do the next step and load your class:
C#
using Newtonsoft.Json;

var rawJson = @"[{
	""id"": 120,
	""trackingNo"": ""683123690493"",
	""sname"": ""AMAN SALES SDN BHD"",
	""sphone"": ""019-8824500"",
	""saddress1"": ""NO 39/39A,JALAN 23 TAMAN"",
	""saddress2"": ""BUKIT KUCHAI"",
	""scity"": ""PUCHONG"",
	""spostcode"": ""47100"",
	""sstate"": ""Selangor"",
	""dairport"": ""KUL"",
	""scountry"": ""MY"",
	""detailOfContent"": ""PARTS"",
	""weight"": 5.0,
	""productPackages"": 1,
	""dimensionX"": 40.0,
	""dimensionY"": 28.0,
	""dimensionZ"": 26.0,
	""chargebleRate"": 5.0,
	""rname"": ""AMAN SALES & SERVICES (M) SDN BHD"",
	""rphone"": ""089-880757"",
	""raddress1"": ""LOT13 NEW KIMBELL INDUSTRIAL"",
	""raddress2"": ""ESTATE,MDLD 4974,JALAN KIMBELL 91100"",
	""rpostcode"": ""91100"",
	""rcity"": ""LAHAD DATU"",
	""rstate"": ""Sabah"",
	""rairport"": ""LDU"",
	""rcountry"": ""MY"",
	""rremark"": ""PLEASE DEL  ASAP"",
	""rvia"": ""BKI"",
	""serviceModeId"": null,
	""agentId"": null
}]";


var result = JsonConvert.DeserializeObject<List<Response>>(rawJson);

Console.WriteLine($"ID: {result!.First().Id}");


Check out the following article for a more in-depth discussion on this topic: Working with Newtonsoft.Json in C# & VB[^]

Hope this helps!
 
Share this answer
 
v2
Comments
Maideen Abdul Kader 31-Oct-22 3:14am    
Hi Grant. First of all I thank you for advice "not posting Bearer Token". Accepted your advice.
Json Data are from remote/externals API url when i have debugged.I have changed class as per.
But still same error when debugging. Pls advice me...
Thank you
Graeme_Grant 31-Oct-22 3:52am    
I am not sure what you are asking. I have shown you a working solution.

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