Solved

JSON response syntax

Posted on 2016-08-04
3
79 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 32

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 32

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Querying data Linq asp.net mvc 8 66
json example 39 115
json value get in input box 6 45
Save signature to file 7 46
We will take a look at the d3.js library for visualizations.  I will provide a walkthrough of a short bar graph example as well as introduce you to the d3.js API.  We also will explore links of other examples and further information regarding SVG's.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

746 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now