Solved

JSON response syntax

Posted on 2016-08-04
3
123 Views
Last Modified: 2016-08-08
I receive a JSON response in the following syntax, where it is returned as objects and not array. Is this right?

{
   "status": "OK",
   "product":
   {
     "name": "ABC",
     "code": "A",
     "Price": "2.5",
     "active": true,
     "contact":
      {
          "name": "X",
          "phone": "999-999-9999",
          "email": "X@company.com"
      }  
   }
}

I use the following code to access it and it throws error. Object serialized to Object. JArray instance expected.
This code would work if the "product" was returned as an array.

 Dim parsedObject = JObject.Parse(response)
           
 Dim docs = JArray.FromObject(parsedObject("product")).Select(Function(x) x.ToObject(Of Product)())
 Dim productDetail = docs.Select(Function(x) x).OrderBy(Function(x) x.name).ToList


Public Class Product
        Public Property name As String
        Public Property code As String
        Public Property price As Decimal
        Public Property active As Boolean
 End Class

Do I need to access the JSON response differently or is the response syntax wrong?
0
Comment
Question by:Angel02
  • 2
3 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 41742891
Your JSON object translates loosely to this:
Class JsonData
	Public Property Status() As String
	Public Property [Product]() As Product
End Class

Class Product
	Public Property Name() As String
	Public Property Code() As String
	Public Property Price() As String
	Public Property Active() As Boolean
	Public Property [Contact]() As Contact
End Class

Class Contact
	Public Property Name() As String
	Public Property Phone() As String
	Public Property Email() As String
End Class

Open in new window


Example -
Imports Newtonsoft.Json
Imports System.Reflection
Imports System.Runtime.CompilerServices

Module Module1
	Const json = "{""status"": ""OK"",""product"":{""name"": ""ABC"",""code"": ""A"",""Price"": ""2.5"",""active"": true,""contact"":{""name"": ""X"",""phone"": ""999-999-9999"",""email"": ""X@company.com""}}}"
	Sub Main()
		Dim response = JsonConvert.DeserializeObject(Of JsonData)(json)
		Console.WriteLine(response.ToString())
		Console.ReadLine()
	End Sub
End Module

Class JsonData
	Public Property Status() As String
	Public Property [Product]() As Product

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Class Product
	Public Property Name() As String
	Public Property Code() As String
	Public Property Price() As String
	Public Property Active() As Boolean
	Public Property [Contact]() As Contact

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Class Contact
	Public Property Name() As String
	Public Property Phone() As String
	Public Property Email() As String

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Module Extensions
	<Extension()> _
	Public Function GetPropertiesString(Of T)(source As T) As String
		Dim result = String.Empty
		If source IsNot Nothing Then
			result = String.Join("; ", (From [property] As PropertyInfo In GetType(T).GetProperties() Select String.Format("{{ {0}, {1} }}", [property].Name, [property].GetValue(source, Nothing))))
		End If
		Return result
	End Function
End Module

Open in new window

Produces the following output -Capture.JPG
In the future, you can use http://json2csharp.com/ in order to generate c# classes.  Translating these classes into VB.NET is relatively straigthforward; e.g. the classes from your presented json are generated as:
public class Contact
{
    public string name { get; set; }
    public string phone { get; set; }
    public string email { get; set; }
}

public class Product
{
    public string name { get; set; }
    public string code { get; set; }
    public string Price { get; set; }
    public bool active { get; set; }
    public Contact contact { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public Product product { get; set; }
}

Open in new window


-saige-
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41747354
For this particular response it makes no sense as it deserializes into a distinct object.  An example of response that deserialized into a list of objects would be something along the lines of:
Imports Newtonsoft.Json
Imports System.Reflection
Imports System.Runtime.CompilerServices

Module Module1
	Const json = "[{""status"": ""OK"",""product"":{""name"": ""ABC"",""code"": ""A"",""Price"": ""2.5"",""active"": true,""contact"":{""name"": ""X"",""phone"": ""999-999-9999"",""email"": ""X@company.com""}}},{""status"": ""FAIL"",""product"":{""name"": ""DEF"",""code"": ""D"",""Price"": ""3.5"",""active"": true,""contact"":{""name"": ""Y"",""phone"": ""999-999-9999"",""email"": ""Y@company.com""}}},{""status"": ""OK"",""product"":{""name"": ""GHI"",""code"": ""G"",""Price"": ""1.5"",""active"": false,""contact"":{""name"": ""Z"",""phone"": ""999-999-9999"",""email"": ""Z@company.com""}}},{""status"": ""FAIL"",""product"":{""name"": ""JKL"",""code"": ""J"",""Price"": ""4.5"",""active"": true,""contact"":{""name"": ""A"",""phone"": ""999-999-9999"",""email"": ""A@company.com""}}},{""status"": ""OK"",""product"":{""name"": ""MNO"",""code"": ""M"",""Price"": ""0.5"",""active"": false,""contact"":{""name"": ""B"",""phone"": ""999-999-9999"",""email"": ""B@company.com""}}}]"
	Sub Main()
		Dim response = JsonConvert.DeserializeObject(Of Products)(json)
		Console.WriteLine("FAILURES")
		For Each [product] In response.Where(Function(x) x.Status.Equals("fail", StringComparison.OrdinalIgnoreCase))
			Console.WriteLine([product])
		Next
		Console.WriteLine()
		Console.WriteLine("IN-ACTIVE")
		For Each [product] In (From p In response Where Not p.Product.Active Select p)
			Console.WriteLine([product])
		Next
		Console.WriteLine()
		Console.WriteLine("COST LESS THAN 2")
		For Each [product] In (From p In response Where Convert.ToDecimal(p.Product.Price) < 2D Select p)
			Console.WriteLine([product])
		Next
		Console.ReadLine()
	End Sub
End Module

Class Products
	Inherits List(Of JsonData)

	Public Sub New()
		MyBase.New()
	End Sub

	Public Sub New(capacity As Integer)
		MyBase.New(capacity)
	End Sub

	Public Sub New(collection As IEnumerable(Of JsonData))
		MyBase.New(collection)
	End Sub
End Class

Class JsonData
	Public Property Status() As String
	Public Property [Product]() As Product

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Class Product
	Public Property Name() As String
	Public Property Code() As String
	Public Property Price() As String
	Public Property Active() As Boolean
	Public Property [Contact]() As Contact

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Class Contact
	Public Property Name() As String
	Public Property Phone() As String
	Public Property Email() As String

	Public Overrides Function ToString() As String
		Return Me.GetPropertiesString()
	End Function
End Class

Module Extensions
	<Extension()> _
	Public Function GetPropertiesString(Of T)(source As T) As String
		Dim result = String.Empty
		If source IsNot Nothing Then
			result = String.Join("; ", (From [property] As PropertyInfo In GetType(T).GetProperties() Select String.Format("{{ {0}, {1} }}", [property].Name, [property].GetValue(source, Nothing))))
		End If
		Return result
	End Function
End Module

Open in new window

Which produces the following output -Capture.JPG-saige-
0
 

Author Comment

by:Angel02
ID: 41747806
Got it. Thanks!
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JSON Syntax Error 8 45
Loop through JSON response returned by JSON.Net 2 111
WCF Rest JSON Serialization 12 125
Add json string to a javascript object 9 71
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question