Tech or Treat! Write an article about your scariest tech disaster to win gadgets!Learn more

x
?
Solved

JSON response syntax

Posted on 2016-08-04
3
Medium Priority
?
209 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 34

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 34

Accepted Solution

by:
it_saige earned 2000 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

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, …
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.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

649 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