Json deserialization multiple object - json

I got the problem deserializing the object.
Currently I have two objects that need to be deserialized but I only can input one. How to I achieve that?
Here my code:
Public Function PostContract(ByVal data As String) As String Implements IEchoTest.PostContract
Dim biz As New ContractBiz
Dim response As New ContractModel.ContractResponse
Dim request As String = data
'[Convert to entity data and pass to Business Layer]
response = biz.CreateContract(JsonConvert.DeserializeObject(Of Contract)(request))
Return JsonConvert.SerializeObject(response)
End Function

Related

JSON deserialization error with Azure translation services

I am building a program in Visual Studio 2017 in Windows Forms - sorry but that's the only thing I know how to use - anyway, most everything for this is C#, so I've been having trouble getting help.
I have translated the Microsoft provided example for a C# program to connect to Azure Cognitive Translation services, signed up, got all my keys, etc.
When I run the code, I get the following error:
Newtonsoft.Json.JsonSerializationException:
'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
System.Collections.Generic.List1[System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[System.Collections.Generic.Dictionary2[System.String,System.String]]]]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'error', line 1, position 9.'
I have tried too many things to list from many different sources. I do not know a whole lot about JSON and am asking for help with the code to solve the above issue.
Public Class DetectedLanguage
Public Property language As String
Public Property score As Double
End Class
Public Class Translation
Public Property text As String
Public Property two As String
End Class
Public Class Example
Public Property detectedLanguage As DetectedLanguage
Public Property translations As Translation()
End Class
Dim textToTranslate As String = root
Dim fromLanguage As String
Dim fromLanguageCode As String = cabbr
Dim toLanguageCode As String = "en"
Dim endpoint As String = String.Format(TEXT_TRANSLATION_API_ENDPOINT, "translate")
Dim uri As String = String.Format(endpoint & "&from={0}&to={1}", fromLanguageCode, toLanguageCode)
Dim body As System.Object() = New System.Object() {New With {Key .Text = textToTranslate}}
Dim requestBody = JsonConvert.SerializeObject(body)
Using client = New HttpClient()
Using request = New HttpRequestMessage()
request.Method = HttpMethod.Post
request.RequestUri = New Uri(uri)
request.Content = New StringContent(requestBody, Encoding.UTF8, "application/json")
request.Headers.Add("Ocp-Apim-Subscription-Key", COGNITIVE_SERVICES_KEY)
request.Headers.Add("Ocp-Apim-Subscription-Region", "westus")
request.Headers.Add("X-ClientTraceId", Guid.NewGuid().ToString())
Dim response = client.SendAsync(request).Result
Dim responseBody = response.Content.ReadAsStringAsync().Result
Dim result = JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, List(Of Dictionary(Of String, String)))))(responseBody)
Dim translation = result(0)("translations")(0)("text")
rtRoot.Text = translation
End Using
End Using
I have already used the jsonutil site to paste my JSON code in and get the classes.
Here is my JSON content:
[
{
"detectedLanguage":{
"language":"nl",
"score":1.0
},
"translations":[
{
"text":"bord vervangen en uitvoerig getest",
"to":"nl"
},
{
"text":"Board replaced and tested extensively",
"to":"en"
}
]
}
]
OK!!! after playing around with this - Jimi - your solution worked!!! thank you SO much! i had to remove the following to lines: request.Headers.Add("Ocp-Apim-Subscription-Region", "westus") request.Headers.Add("X-ClientTraceId", Guid.NewGuid().ToString())

How to parse Poloniex Json into VB Net Object?

I'm currently pulling in the Poloniex returnCompleteBalances info in the following JSON format:
{"LTC":{"available":"5.015","onOrders":"1.0025","btcValue":"0.078"},"NXT:{...} ... }
I am trying to add the info to a class I made, and separate the different coins(property names) and their associated info. So far I have the following:
Sub GetBalances()
Dim method As String = calldata("returnCompleteBalances")
Dim allData As JObject = JObject.Parse(method)
Dim coinlist As New List(Of balancedata)
For Each token As JToken In allData("objects")
Dim prop As JProperty = token
coinlist.Add(New balancedata With {.Coin = prop.Name, .available = prop.Value("available"), .onOrders = prop.Value("onOrders"), .btcValue = prop.Value("btcValue")})
Next
End Sub
And the class
Public Class balancedata
Public Property Coin As String
Public Property available As Decimal
Public Property onOrders As Decimal
Public Property btcValue As Decimal
End Class
When I run the code, I receive an error on the for each token as Jtoken line that reads: "Object reference not set to an instance of an object"
How do I resolve this? I do not know all of the values for the property name, LTC, BTC, etc. so I am trying to look through them all and itemize the associated values into a list.

Attach JSON data to be used by view in MVC application

I have a very simple application that I am using to learn move about MVC. In that application I search some data and return a JSON string that I want to use as the model for the view. I just can't seem to figure out how to get the view to consume the JSON as a set of data for it to show on screen.
The code I have so far:
Function Find(term As String) As ActionResult
Dim model As String = SearchData(term)
Return View(model)
End Function
SearchData returns a JSON string that can have one or many objects in it.
How do I now take the JSON returned from SearchData and use it in a view? In fact, when I attempt to add a view it wants to know what model to use. How do i also specific that?
Create a strongly typed object to store you data when parsed
Public Class Data
Public Property ID As Integer
Public Property Term As String
Public Property SomeProperty As String
Public Property SomeOtherProperty As String
End Class
Using a library like JSON.Net, parse the JSON returned from the search.
This assumes a collection of Data is returned from the search.
Imports Newtonsoft.Json;
Function Find(term As String) As ActionResult
Dim json As String = SearchData(term)
Dim model As List(Of Data) = JsonConvert.DeserializeObject(Of List(Of Data))(json)
Return View(model)
End Function
Let the view know to expect the strongly typed model.
#ModelType List(Of Data)
#Code
ViewData("Title") = "Find"
End Code
<h2>MyView</h2>
<!-- rest of view where model can be accessed -->

Deserializing Json VB.NET

I am trying to deserialize data from a webserver for a game launcher.
The API docs provide me the data in json format, but I have been struggling to be able to read that data I am given and store it as a variable to use to log in a player. I have also tried a few other things but I am just stuck now. Normally a response from the server would like like this:
{"success":"true","gameserver":"gameserver-alpha.toontownrewritten.com","cookie":"deadbeefdeafbeef0x123"}
The code to deserialize the data:
Dim result() As TTRServerResponse = JsonConvert.DeserializeObject(Of TTRServerResponse())(responseFromServer)
Class with the variables I want to store
Public Class TTRServerResponse
Public Property success As String
Public Property eta As String
Public Property position As String
Public Property queueToken As String
Public Property cookie As String
End Class
Any ideas where I messed up or what I should do? Thanks, Ben.
EDIT: Finally figured it out, I needed to change my result to: Dim result As TTRServerResponse = JsonConvert.DeserializeObject(Of TTRServerResponse) (responseFromServer) I also was returning the data incorrectly to my other sub by returning just result. What I needed to do was return result.success. I now have a better understanding.
You are trying to deserialize the JSON into an array but in your example it is a single object.
So assuming
Dim responseFromServer As String
is equal to
{"success":"true","gameserver":"gameserver-alpha.toontownrewritten.com","cookie":"deadbeefdeafbeef0x123"}
Which, according to the documentation you linked to, is suppose to be a single object,
then you need to update your code to deserialize a single object as appose to an array
Dim result As TTRServerResponse = JsonConvert.DeserializeObject(Of TTRServerResponse)(responseFromServer)

Convert JSON object array value to string array in VB.NET without loop

I've a JSON object array like this
dim d as string="[{name:'alex',age:20,id:1},{name:'John',age:22,id:2},
{name:'Philip',age:26,id:3},{name:'Mathew',age:27,id:4},
{name:'James',age:30,id:5},{name:'Antony',age:20,id:6},
{name:'Kevin',age:10,id:7}]"
I parsed the JSON string array using JSON serializer as this way.
DIM mj() as mysample
dim js as new javascriptserializer
mj=js.deserialize(Of mysample)(d)
But my requirement is to convert one attribute value of that json object to a string array based on a condition. For example the result array should contain all name with age 20.
The array should be ['Antony','Alex']
How can we achieve this without any loop. I mean some solution using LINQ
You can create a class with the properties found in you json, then use a library like newtonsoft to serielize your json to a list of object using your new class
public class Person{
public string name {get;set;}
public string age {get;set;}
}
List<Person> personList = JsonConvert.DeserializeObject<List<Person>>(jsonString);
Then use this list to run a linq to find the ones with age = 20
List<string> result = from personList.select(new {age = age}).where(p => p.age == 20)
This code is not tested just to provide a guide to the result.