Make .Net Web API JSON output pretty - json

I'm using code below to get data in JSON format using Newtonsoft.Json:
my code to create the JSON is
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim writer As JsonWriter = New JsonTextWriter(sw)
writer.WriteStartArray()
For Each elements As JToken In result
If i = 0 Then
i += 1
Continue For
End If
For Each aaa As JToken In elements
writer.WriteStartObject()
Dim pmid = aaa("uid").Value(Of String)
Dim issn = aaa("issn").Value(Of String)
Dim essn = aaa("essn").Value(Of String)
Dim source = aaa("source").Value(Of String)
Dim sortpubdate = aaa("sortpubdate").Value(Of String)
writer.WritePropertyName("pmid")
writer.WriteValue(pmid)
writer.WritePropertyName("journal")
writer.WriteValue(source)
writer.WritePropertyName("issn")
writer.WriteValue(issn)
writer.WritePropertyName("essn")
writer.WriteValue(essn)
writer.WritePropertyName("sortpubdate")
writer.WriteValue(sortpubdate)
writer.WritePropertyName("pubYear")
writer.WriteEndObject()
Next
Next
writer.Close()
Return sb.ToString
and the output code is
public HttpResponseMessage Get()
{
string yourJson = GetJsonFromSomewhere();
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
return response;
}
My current output is.
[{"pmid":"29241721","issn":"0749-3797","essn":"1873-2607","journal":"Am J Prev Med","pubYear":"2018","ImpactFactor":" 4.127"},{"pmid":"28987617","issn":"0166-4328","essn":"1872-7549","journal":"Behav Brain Res","pubYear":"2018","ImpactFactor":" 3.173"},
Is there a way I can indent my output?
[{
"pmid": "29241721",
"issn": "0749-3797",
"essn": "1873-2607",
"journal": "Am J Prev Med",
"pubYear": "2018",
"ImpactFactor": " 4.127"
}, {
Is there a way I can do it like below?
this.SerializerSettings.Formatting = Formatting.Indented;
The client side is just a simple browser URL that get a response

You should indent your object in serialization time and then use it everywhere you want. If GetJsonFormatSomewhere() is your serialization method you should seralize your object in that method below:
var serializedObject = JsonConvert.SerializeObject(data, Formatting.Indented);
and then pass indented object to StringContent method.
Note: it's better to indent your output in client side, that way your packet size will stay small and it's performance friendly.

I got what I needed with
Dim writer As JsonWriter = New JsonTextWriter(sw)
writer.Formatting = Newtonsoft.Json.Formatting.Indented

Related

Json with parameters in Vb.net

I need to send json data to an API including a QR code and some other values.
this is what i got from them
The needed parameter is:
• Parameter "data" in JSON:
id -> 100 (fixed, it is the ID needed for our software)
qrcode -> QRcode value
Example: data={"id":"100","qrcode":"VL11bbdb186a3a6dcfc57a1b07149c9a0e"}
and this is the code i use
Call:
Dim jsonPost As New JsonPost(postadress)
Dim dictqr As New Dictionary(Of String, Object)
dictqr.Add("id", lastmeas.id)
dictqr.Add("qrcode", lastmeas.qrcode)
jsonPost.PostData(dictqr)
and this is the definition
Public Class JsonPost
Private urlToPost As String = ""
Public Sub New(ByVal urlToPost As String)
Me.urlToPost = urlToPost
End Sub
Public Function PostData(ByVal dictData As Dictionary(Of String, Object)) As Boolean
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte
ServicePointManager.ServerCertificateValidationCallback = Function(o, certificate, chain, errors) True
Try
webClient.Headers("content-type") = "application/json"
webClient.Headers("accept") = "*/*"
reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dictData, Newtonsoft.Json.Formatting.None))
resByte = webClient.UploadData(Me.urlToPost, "POST", reqString)
resString = Encoding.Default.GetString(resByte)
Form1.respuesta_envio = resString
webClient.Dispose()
Return True
Catch ex As Exception
Form1.respuesta_envio = ex.Message
CreateObject("WScript.Shell").Popup(ex.Message, 5, "Data not transfered")
End Try
Return False
End Function
End Class
if i deserialize, i get
{"id":"100","qrcode":"example"}
but i do not know how to include this data= part
The API appears to be asking you to send a JSON string inside a form-url-encoded parameter. That's unpleasant and not a logical way to design an API, but if that's what they require then that's what you'll have to do.
Therefore you need to:
remove the Content-Type header telling the server to expect a JSON body in the request. What you'll actually be sending is form-url-encoded data where the one parameter happens to contain JSON within its value. i.e. remove this line:
webClient.Headers("content-type") = "application/json"
prepend the data= bit to the JSON string generated by the SerializeObject function:
reqString = Encoding.Default.GetBytes("data=" & JsonConvert.SerializeObject(dictData, Newtonsoft.Json.Formatting.None))

Parse Json in VB.NET with "Newtonsoft" Json.net

How to Parse Json in vb.net; want to create bittrex ticker.
Request I made with following code:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-ltc"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
rawresp = reader.ReadToEnd()
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
And i got following json response:
{"success":true,"message":"","result":[{"MarketName":"BTC-LTC","High":0.01670094,"Low":0.01610000,"Volume":47495.02156742,"Last":0.01628948,"BaseVolume":777.22088098,"TimeStamp":"2018-01-21T13:18:23","Bid":0.01624001,"Ask":0.01628948,"OpenBuyOrders":2146,"OpenSellOrders":8104,"PrevDay":0.01622000,"Created":"2014-02-13T00:00:00"}]}
Want value of Last to be shown in textbox, so i tried to parse it with "Newtonsoft" as follows:
Dim jsonArray As JArray = JArray.Parse(rawresp)
For Each item As JObject In jsonArray
textboxLast.Text = item.SelectToken("Last").ToString
Next
But getting error :(
Dim json As String = rawresp
Dim jsonObject As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.Linq.JObject.Parse(json)
Dim jsonArray As JArray = jsonObject("result")
For Each item As JObject In jsonArray
textboxLast.Text = item.SelectToken("Last").ToString
Next
It has to do with the format of the JSON. it is not an array, but an object that contains an array, so you have to first parse the object, and then take the array out of it to parse properly. You missed that one extra step, which I added in above code snippet

Serialized JSON in VB.NET not recognised by web server

I'm new to VB.NET and am working on a simple program that will serialize two variables into JSON and POST the data to a web server. The data is being received by the Python server but it is giving an error when trying to deserialize the data.
The inputs are:
tester_id = 2
operation = "P"
When serialized this looks like:
{
"tester_id": 2,
"operation": "P"
}
Our server is giving an error and has the following log.
[Sat Aug 19 13:46:53.485257 2017] [:error] [pid 17352] <QueryDict: {u'{\\r\\n "tester_id": 2,\\r\\n "operation": "P"\\r\\n}': [u'']}>
This suggests that it is receiving a key of:
{u'{\\r\\n "tester_id": 2,\\r\\n "operation": "P"\\r\\n}
With a value of:
[u'']
This isn't correct and I don't understand why it is being received like this, any help is greatly appreciated! See below for the VB.NET code.
Class:
Public Class JSON_get_sensor_id_POST
Public Property tester_id() As Integer
Get
Return m_tester_id
End Get
Set(ByVal value As Integer)
m_tester_id = value
End Set
End Property
Private m_tester_id As Integer
Public Property operation() As String
Get
Return m_operation
End Get
Set(ByVal value As String)
m_operation = value
End Set
End Property
Private m_operation As String
End Class
Call function:
Dim set_tester_id As Integer = 1
Dim set_operation As String = "P"
Dim manuf_url As String = "https://XYZ...."
Dim JSON_to_send As New JSON_get_sensor_id_POST
JSON_to_send.tester_id = set_tester_id
JSON_to_send.operation = set_operation
Dim postData = JsonConvert.SerializeObject(JSON_to_send, Formatting.Indented)
Dim return_object = POST_to_Server(manuf_url, postData)
Upload Function:
Private Function POST_to_Server(ByVal post_url As String, ByVal JSON_to_post As Object)
Dim user_login As String = "blah#blah.com"
Dim user_pass As String = "blah"
Dim myCache As New CredentialCache()
myCache.Add(New Uri(post_url), "Basic", New NetworkCredential(user_login, user_pass))
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create(post_url)
' Set the Method property of the request to POST.
request.Credentials = myCache
request.Method = "POST"
request.ContentType = "application/json"
' Create POST data and convert it to a byte array.
Dim byteArray As Byte() = Encoding.Default.GetBytes(JSON_to_post)
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Display the status.
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
DebugMessage(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
Dim myObject = JsonConvert.DeserializeObject(Of JSON_sensor_id_request_return)(responseFromServer)
Return myObject
End Function
\r and \n are escape sequences that are not visible when a string is displayed. Instead of formatting your data like this:
{
"tester_id": 2,
"operation": "P"
}
try formatting it something like this:
{"tester_id": 2,"operation": "p"}

How to save a json file from an API in vb.net

I have an API where I consume a Json file from. The function I have written is
Public Function getData(ByVal _token As String, ByVal _identifier As String) As String
Dim client = New RestClient(_baseURI)
Dim request = New RestRequest("/datasources/{identifier}/data", Method.GET)
request.AddUrlSegment("identifier", _identifier)
request.AddHeader("Authorization", "Basic " + _token)
Dim jstr = client.Execute(request).Content
Dim allDATA As List(Of GeneralInfo) = JsonConvert.DeserializeObject(Of List(Of GeneralInfo))(jstr)
Return 0
End Function
This works perfectly well. I can save the string into a file. But I also need a json file and I just do not know how to accomplish this.
Based on this solution I tried
request.OnBeforeDeserialization = Function(resp)
resp.ContentType = "appliction/json"
End Function
Dim queryResult = client.Execute(request)
Console.WriteLine(queryResult.Content)
but without any result. Nothing will be written into the console. Any idea how I can get the json file? I am using
Imports Newtonsoft.Json
Imports RestSharp

Get response body

I'am currenty using code :
Private Function getHtmlres(ByVal response As HttpWebResponse) As String
Dim myWebSource As New StreamReader(response.GetResponseStream())
Dim myPageSource As String = String.Empty
myPageSource = myWebSource.ReadToEnd()
Return myPageSource
End Function
But the problem is that I'm downloading audio/mpeg object. When I see the
MsgBox(getHtmlres(myHttpWebResponse1))
It shows :
ID3<<<SQUARE>>>
. When I do
System.IO.File.WriteAllText("D:\sdg.txt",getHtmlres(myHttpWebResponse1))
it writes 0 bytes.