0

how to create an array that if we convert into json we have the result below.

{{"name":"first_example_1"}, {"name": "second_example_1"}}

I tried using this

dim x as jArray
x.add("first_example_1")
x.add("second_example_1")

but when I try to convert the above to json I get this

{"firstname_example_1", "second_example_1"}

How can I add an index?

2 Answers 2

1

try this

        Dim jArray(1) As Object
        jArray(0) = New With {Key .name = "second_example_1"}
        jArray(1) = New With {Key .name = "firstname_example_1"}
        Dim serializer As New JavaScriptSerializer()
        Dim result As String
        result = serializer.Serialize(jArray)

and don't forget to Imports System.Web.Script.Serialization

Sign up to request clarification or add additional context in comments.

1 Comment

I changed my code before I got to read your answer. Based on my question your code works and generate the exact result I want, cool. But I was having hard time de-serializing the object ("due to I'm newbie on VB.net") since I don't have system.web.script.serialization in my reference I don't know why I can't find it on my reference, I only have the system.web.services. Thank you sir. I appreciate it.
0

the above answer of @styx works but I have already change my code. This answer is for additional information only.

I created a class named PerInfo

public class PerInfo
  public firstname
  public lastname
end class

To serialize I wrote this;

dim x as new PerInfo
x.firstname = textbox1.text
x.address = textbox2.text

dim res as string =  JsonConvert.SerializeObject(x)
' the above code produces my desired result which is
' {"firstname":"jeo","address":"GSC"}

To deserialized I did this;

Dim t As PerInfo = JsonConvert.DeserializeObject(Of PerInfo)(x)
'I can now access the `firstname` and `address` via
' t.firstname and t.address

MsgBox(t.firstname & "===" & t.address)

Hope this helps...

PS: I manually added via add reference the Newtonsoft.Json.dll version Net 2.0 for backward compatibility for pc using .net 2.0 framework if I'm right. Feel free to correct me with this.

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.