Reputation: 3185
In my VB.net Web Api, I am using JsonWriter to build a Json Array then pass it to Client Side as a list(Of VerifyReturn) considering VerifyReturn is the name of a class.
Public Class VerifyReturn
Public Property Name as String
Public Property AnotherName as String
End Class
Here's my VB.net code:
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
jsonWriter.WriteStartObject()
jsonWriter.WritePropertyName("Name")
jsonWriter.WriteValue("Value")
jsonWriter.WritePropertyName("AnotherName")
jsonWriter.WriteValue("AnotherValue")
jsonWriter.WriteEndObject()
Dim ReturnJson = JsonConvert.DeserializeObject(Of List(Of VerifyReturn))(sb.ToString)
I am getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[EFramework.VerifyReturn]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
I am new and just learning JSON.
I would like to change the JSON to a JSON array.
How can I do this?
Thanks.
Upvotes: 0
Views: 1544
Reputation: 4033
JSON doesn't allow associative arrays, thus objects are used.
In JSON your example is
{"Name":"Value","AnotherName":"AnotherValue"}
Assuming you want an array with each property as an object that would look like:
[{"Name":"Value"},{"AnotherName","AnotherValue"}]
And your code would look like:
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
jsonWriter.WriteStartArray()
jsonWriter.WriteStartObject()
jsonWriter.WritePropertyName("Name")
jsonWriter.WriteValue("Value")
jsonWriter.WriteEndObject()
jsonWriter.WriteStartObject()
jsonWriter.WritePropertyName("AnotherName")
jsonWriter.WriteValue("AnotherValue")
jsonWriter.WriteEndObject()
jsonWriter.WriteEndArray()
Dim ReturnJson = JsonConvert.DeserializeObject(Of List(Of DifferentClass))(sb.ToString)
Alternatively, if you need a list of your your class, then only wrap an array around it:
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
jsonWriter.WriteStartArray()
jsonWriter.WriteStartObject()
jsonWriter.WritePropertyName("Name")
jsonWriter.WriteValue("Value")
jsonWriter.WritePropertyName("AnotherName")
jsonWriter.WriteValue("AnotherValue")
jsonWriter.WriteEndObject()
jsonWriter.WriteEndArray()
Dim ReturnJson = JsonConvert.DeserializeObject(Of List(Of VerifyReturn))(sb.ToString)
This should result in:
[{"Name":"Value", "AnotherName","AnotherValue"}]
Upvotes: 1