1

I am getting JSON string in result text from the below code.

resp = webRequest.GetResponse
Dim status = resp.StatusCode      
If (status = 200) Then
respStream = New StreamReader(resp.GetResponseStream(), encoding)
resultText = respStream.ReadToEnd()
respStream.Dispose()

result text is

"{""searchResult"":[{""id"":""2430.6086.3435.4713"",""name"":""0000425"",""type"":""Reference"",""revision"":""B.1"",""attribute[Entity.Name]"":""TestPart2"",""current"":""IN_WORK"",""attribute[Entity.ExternalID]"":""0000425""},{""id"":""24360.60586.12065.45796"",""name"":""0000417"",""type"":""Reference"",""revision"":""B.1"",""attribute[Entity.Name]"":""TestPart3"",""current"":""IN_WORK"",""attribute[Entity.ExternalID]"":""0000417""}],""msg"":""OK""}"

I need to create a list of array for each objects in this string( Above result has 2 array in list.Each array will have values.)

As i am very new to JSON.I have no idea about this. I found Newton.Json library in vb.net. How to handle JSON with this library?

usmanharoon
  • 173
  • 2
  • 13
  • If you're comfortable using XML instead of a collection of objects, I have an open source JSON to XDocument parser here: https://github.com/dday9/.NET-JSON-Transformer – David Mar 12 '20 at 22:47

1 Answers1

1

The easy way is to go to http://app.quicktype.io and paste the JSON in there (you'll have to turn the double quotes into single with a notepad find/replace, and remove the leading and trailing quotes; your JSON seems double encoded at the moment)

QuickType will generate you a bunch of C# representing the JSON and some helper methods to serialize and deserialize it

Then use some other service to convert the C# to VB.NET - the two languages compile to The same thing underneath so there are plenty of converters out there. Telerik's one didn't work when I tried, neither did codefusion's but https://codeconverter.icsharpcode.net/ produced this, which looks fairly sane:

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Converters
Imports System.Runtime.CompilerServices

Namespace QuickType
    Public Partial Class A
        <JsonProperty("searchResult")>
        Public Property SearchResult As SearchResult()
        <JsonProperty("msg")>
        Public Property Msg As String
    End Class

    Public Partial Class SearchResult
        <JsonProperty("id")>
        Public Property Id As String
        <JsonProperty("name")>
        Public Property Name As String
        <JsonProperty("type")>
        Public Property Type As String
        <JsonProperty("revision")>
        Public Property Revision As String
        <JsonProperty("attribute[Entity.Name]")>
        Public Property AttributeEntityName As String
        <JsonProperty("current")>
        Public Property Current As String
        <JsonProperty("attribute[Entity.ExternalID]")>
        Public Property AttributeEntityExternalId As String
    End Class

    Public Partial Class A
        Public Shared Function FromJson(ByVal json As String) As A
            Return JsonConvert.DeserializeObject(Of A)(json, Settings)
        End Function
    End Class

    Public Module Serialize
        <Extension()>
        Public Function ToJson(ByVal self As A) As String
            Return JsonConvert.SerializeObject(self, Settings)
        End Function
    End Module

    Friend Module Converter
        Public ReadOnly Settings As JsonSerializerSettings = New JsonSerializerSettings With {
            .MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            .DateParseHandling = DateParseHandling.None
        }
    End Module
End Namespace

You'd use it like:

Dim myJsonAsAnObject = A.FromJson(your_DECODED_json_string_variable_here)
myJsonAsAnObject.SearchResult(0).Name = "this is a new name"
Dim strJson = myJsonAsAnObject.ToJson()

The only thing left to possibly figure out is what to do about the remote service that is sending you broken JSON; it's JSON, but then encoded as JSON, so it's essentially a string that contains JSON, when it should just be JSON, looking like:

{
  "searchResult": [
    {
      "id": "2430.6086.3435.4713",
      "name": "0000425",
      "type": "Reference",
      "revision": "B.1",
      "attribute[Entity.Name]": "TestPart2",
      "current": "IN_WORK",
      "attribute[Entity.ExternalID]": "0000425"
    },
    {
      "id": "24360.60586.12065.45796",
      "name": "0000417",
      "type": "Reference",
      "revision": "B.1",
      "attribute[Entity.Name]": "TestPart3",
      "current": "IN_WORK",
      "attribute[Entity.ExternalID]": "0000417"
    }
  ],
  "msg": "OK"
}

It's being caused because the person who wrote the web service decided to serialize some object to a string and return the string, which the web server then encoded again. What should have been done is just return the object. That is to say the web service shoudl look like this:

 'controller function
 Function GetWhatever() Returns ActionResult 
     Dim x as New Whatever
     x.Id = "24360.60586.12065.45796"
     x.Name = "0000417"
     x.Type = type": "Reference"

     Dim s as String = JsonEncodeMethod(x)

     return Json(s)
  EndFunction

When it should have looked like:

 'controller function
 Function GetWhatever() Returns ActionResult 
     Dim x as New Whatever
     x.Id = "24360.60586.12065.45796"
     x.Name = "0000417"
     x.Type = type": "Reference"

     return Json(x)
  EndFunction

Final point of note (i know, i'm going on a bit now). Make sure that you haven't thrown a huge red herring in here by using the debugger to extract the value of the resultText like this guy did - in his screenshot and in his text you can see that the tooltip and the SO question contain the same string, but the problem is the tooltip text in visual studio debugger adds another level of string encoding...

So it might be, depending on how you got that resultText to paste here, that most of this "it has been double encoded" advice isn't the case, because resultText contains:

{
  "searchResult": [
    {
      "id":
...

But your copying it out of visual studio caused it to become:

"{
  ""searchResult"": [
    {
      ""id"":
...

If in doubt, Console.WriteLine() it and copy the result from the console

pps; attribute[Entity.Name] and attribute[Entity.ExternalID] look wonky. not really sure why this wasn't JSON'd as ..., "entity": { "name": "testPart3", "externalID": "0000417" }, ... by the person that wrote the service. I'd fix that too

Caius Jard
  • 72,509
  • 5
  • 49
  • 80