1

I am trying to parse a Json String that is returned let is say from a service. For simplicity it will be like:

Dim jsonstring = _
<s>
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
  {"value": "New", "onclick": "CreateNewDoc()"},
  {"value": "Open", "onclick": "OpenDoc()"},
  {"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
</s>.Value

Now I am using the following function to read the json string to an object however all the properties are always nothing. I have created an object for each json object in the above string and the object has Datacontract and Datamember attributes. Any tips please?

Dim menu = JsonObject(Of Menu)(jsonstring)
    Console.WriteLine(menu.value)

Private Function JsonObject(Of t)(jsonString As String) As t
    Dim ser As New DataContractJsonSerializer(GetType(t))
    Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(jsonString))
    ms.Position = 0
    Dim obj As t = DirectCast(ser.ReadObject(ms), t)
    Return obj
End Function

2 Answers 2

1

By looking at this call:

Console.WriteLine(menu.value)

I am suspecting that the Menu class is not defined correctly... Does your Menu class has a property called 'menu' and does the type of this 'menu' property is a complex type with the properties called 'id', 'value', 'popup'?

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

Comments

0

Thanks for the reply.

I used Json2cshap.com to convert this Json String to classes. The classes (c#) version looks like this. The only difference is that mine is VB.net and all classes / properties have and attributes.

public class Menuitem
{
    public string value { get; set; }
    public string onclick { get; set; }
}

public class Popup
{
    public List<Menuitem> menuitem { get; set; }
}

public class Menu
{
    public string id { get; set; }
    public string value { get; set; }
    public Popup popup { get; set; }
}

public class RootObject
{
    public Menu menu { get; set; }
}

Should the root object (RootObject) to be called Menu? I cannot test it right now but give your suggestion a go.

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.