Solved

JSON response syntax

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

Title # Comments Views Activity
C# Linq to Get XML 38 79
Correct javascript syntax to extract jSON array data? 1 63
Code works but how can I download the file? 20 67
how to read json value 2 32
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.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

863 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

25 Experts available now in Live!

Get 1:1 Help Now