Solved

JSON response syntax

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
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…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

810 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