1

I have the following code:

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Module Module1

Structure JSONList
    Dim Name, Email As String
    Dim Age As Integer
End Structure

Sub Main()
    Dim Data(1) As JSONList

    Data(0).Name = "Josh"
    Data(0).Age = 17
    Data(0).Email = "[email protected]"
    Data(1).Name = "Greg"
    Data(1).Age = 17
    Data(1).Email = "[email protected]"

    Dim JSONEncode As String
    JSONEncode = JsonConvert.SerializeObject(Data)
    Console.WriteLine(JSONEncode)
    Console.WriteLine()
    Console.WriteLine()

    Dim JSONDecode() As JSONList = JsonConvert.DeserializeObject(JSONEncode)
    Console.WriteLine(JSONDecode(0).Name)

    Console.ReadKey()


End Sub

End Module

The first encoding part of the script is used to store the encoded string to a database, the output is:

[{"Name":"Josh","Email":"[email protected]","Age":17},{"Name":"Greg","Email":"[email protected]","Age":17}]

Now when I try to decode this JSON string, I get an error Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'JSONList[]'.

I need the data to be encoded in the JSON format so that I can use it in my website that uses PHP to decode it. I am using Visual Basic 2010 along with JSON.NET.

2 Answers 2

1

The problem is that JsonConvert.DeserializeObject deserialises into an object of type Newtonsoft.Json.Linq.JArray which .net cannot automatically convert to an array of JSONList. A little bit of conversion is required:

Dim jsonObject As Newtonsoft.Json.Linq.JArray =
                                        JsonConvert.DeserializeObject(JSONEncode)

Dim JSONDecode() As JSONList = (
                                 From j In jsonObject
                                 Select New JSONList() With {.Age = j("Age"),
                                                             .Email = j("Email"),
                                                             .Name = j("Name")}
                               ).ToArray()
Sign up to request clarification or add additional context in comments.

Comments

0

As @Adrian said, JsonConvert.DeserializeObject will deserialize to JArray, which .Net cannot automatically convert into an array of your JSONList structure. However, you don't need to do manual conversion; you simply need to use the overload of DeserializeObject which accepts a type parameter. This will allow Json.Net to deserialize directly to your type without needing any special conversion code.

Dim JSONDecode() As JSONList = _
                 JsonConvert.DeserializeObject(Of JSONList())(JSONEncode)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.