Separate JSON objects with JSON.NET (vb) - json

I am having trouble separating pieces of a JSON object. Inside the json string there are 3 objects. One is called "JSONData", which I need to separate into its own object. I have tried so many things I'm starting to lose track. Two of which that seems to have been most helpful are below. However, they both end up empty. No errors, just empty. Hopefully someone can help!!
Dim j As String = JsonConvert.SerializeXmlNode(xml) 'Started out as XML
Dim o As JObject = JsonConvert.DeserializeObject(j) 'Then Json String to JObject
Dim channel As JObject = DirectCast(o("JSONData"), JObject) 'Try #1 to separate
'/// or
Dim jsondata As String = o.Item("JSONData") 'Try #2
'/// i have tried both above with ("IMSXMLLog.JSONData") as well. Same Result.
https://jsfiddle.net/jharris8567/v23kj42v/ - Full JSON

JSONData is inside another object IMSXMLLog, so your inclination to use the path IMSXMLLog.JSONData is correct. However, the indexer on JToken does not support paths, only single property names. To use path syntax you need to use the SelectToken method:
Dim data as JObject = DirectCast(o.SelectToken("IMSXMLLog.JSONData"), JObject)
Fiddle: https://dotnetfiddle.net/Wu70Tu

Related

Output array to excel with VBA

Im am trying to output an array coming from JsonConverter to excel but I get an error 1004:
Sub test()
Dim parsed As Object
Dim myArray As Variant
Set parsed = JsonConverter.ParseJson("{""a"":123,""b"":[1,2,3,4],""c"":{""d"":456}}")
Set myArray = parsed("b")
Set TxtRng = ThisWorkbook.Sheets("Project").Range("A44:D44")
TxtRng.Value = Application.Transpose(myArray)
End Sub
The error is at TxtRng.Value = Application.Transpose(myArray).
Can someone help solve this issue? Thank you.
First: You shouldn't assume that it is commonly known what JsonConverter because it is not a build-in object. I assume you are talking about https://github.com/VBA-tools/VBA-JSON ?
In your example, parsed will return a Dictionary and parsed("b") will return a Collection. Application.Transpose expects a (2-dimensional) array as parameter, but will not work with a collection.
Probably the easiest way to solve this is simply to loop over the collection. Or use a helper function like similar to Converting VBA Collection to Array to create an intermediate array first

add data to a datatable from JSON string - vb.net

I need to know how to populate datatable from JSON string in vb.net code.
the JSON string
{"success":true,"message":"","result":[{"Paper1:null,"StateId":"57ee","School":"1A","Received":"2018-07-03T08:10:05.22","TimeS":"00","STAT":"98","ScoreCard":"76"},{"Paper1:null,"StateId":"52ef","School":"1A","Received":"2018-07-03T08:10:05.22","TimeS":"00","STAT":"88","ScoreCard":"57"}]}
I need to know how to populate above string to a datatable
The above string is in a WebResponse. So is there any way to read the webresponse (here I have used a streamreader, or any other good method) and populate to a datatable?
my code which I got above string.
Dim rqst As WebRequest = WebRequest.Create(uri_variable)
Dim res_p As WebResponse
rqst.Method = "GET"
rqst.Headers.Add("apisign:" & sign)
res_p = rqst.GetResponse()
Dim reader As New StreamReader(res_p.GetResponseStream())
Dim JSON_String as string = reader
P.S: EDIT: I included a screenshot for the user "CruleD"
https://i.stack.imgur.com/EYbP0.png
Heh, this again.
Imports System.Web.Script.Serialization ' for reading of JSON (+add the reference to System.Web.Extensions library)
Dim JSONC = New JavaScriptSerializer().DeserializeObject(JSON_String)
Inspect JSONC with breakpoint. You will see how it looks then you decide what you want to do with it.
Comparing files not working as intended
Similar answer I gave in another thread.
Edit:
JSONC("result")(0)("Quantity")
First you get the contents of "result", then you select which collection you want, in this case first (so 0) then you search for whatever key you want again eg "Quantity" like you did for result originally.
There are other ways to do the same thing, but this one should be pretty straight forward.
There are 3 types of deserialization, check them out if you want.

Using json function with a string in vb.net

When I try to send back a json string with the following json function the string is inserts new lines and escapes characters in vb.net.
Questions
How do I get it to return as proper json?
Is it possible to use something like Json(data:=jsonstr, JsonRequestBehavior.AllowGet) to fix the issue?
Is it possible to use notation similar to C# when dealing with Json strings? Dim someJson as string= #"{""firstname"":"+c.c_firstname+"}"
-
Function get_people_jsonresult(Optional id As Integer = 0) As JsonResult
Dim c As dtb_people = db.dtb_people.Where(Function(x) x.c_Id = 1).Single
Dim jsonstr As String = "{
""firstname"":""" + c.c_firstname + """,
""lastname"":""" + c.c_lastname + """,
""id"":" + c.c_Id.ToString + "
}"
Return Json(jsonstr, JsonRequestBehavior.AllowGet)
End Function
Returned string
"[{\r\n \"firstname\":\"john\",\r\n \"lastname\":\"smith\",\r\n \"id\":1\r\n }]"
updated:
The idea is to figure out different ways to do the same thing to figure out a style that I like.
1) I found this solution but kind of quirky but makes sense - i.e. turn it into an object it will recognize vs. something generic like Ctype(jsonstr, object). I think the point is that jsonresult is meant to serialize json, but this is already serialized, so it should be returned as is.
Dim d As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(jsonstr)
Return Json(d, JsonRequestBehavior.AllowGet)
2) Still not sure if something like this is possible
3) It doesn't look like # offers any benefit since vb.net does multi-line string literals an optional format could be a string interpolation and to use single quotes vs. double so there is no need to escape them.
Dim jsonstr2 As String = $"{{
'firstname': '{c.c_firstname}',
'lastname':'{c.c_lastname}' ,
'id':{c.c_Id.ToString}
}}"
You can return the dtb_people object instead of building the string as below:
Return Json(c, JsonRequestBehavior.AllowGet)
The returned Json will use whatever the property names of your dtb_people class are
If you are wanting to use different property names in your Json, you would decorate your dtb_people class with a JsonProperty declaration and set the PropertyName to whatever you want
[JsonProperty(PropertyName = "firstname")]
The answer to your question which was why it was inserting VBCrLf is because you made a string with some carriage return. Having your string like this on multiple lines will make a string VBCrLf inside it. But #Darthchai has the answer to make your Json

What is wrong with this 1 line code?

dim json2=Newtonsoft.Json.Linq.JObject.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")
The doublequotes are just escape characters. The actual string is
[{"currency_code":"1ST","cash":"0","reserved":"0"},{"currency_code":"8BT","cash":"0","reserved":"0"}]
Which as you can see is a legitimate json.
Basically it looks like a legitimate json array. I want to turn that into an array of strings
Basically I want to turn that into
{
"{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""}",
"{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}"
}
First I parse that into a jobject andd............ I failed.
It's a legitimate json. Why I can't parse that into a jobject?
Some background.
I created 2 json helper function to help me parse any json. One convert json to dictionary. Another parse json into array. In fact, the whole json, is either dictionary (nested or not nested) or array (nested or not nested). Am I correct with this one?
Now the codes are:
Public Shared Function jObjectToDictionary(json As String) As Generic.Dictionary(Of String, String)
Dim json1 = JObject.Parse(json)
Dim dict = json1.ToObject(Of Generic.Dictionary(Of String, Object))
Dim dict2 = dict.ToDictionary(Function(x) x.Key, Function(x) x.Value.ToString)
Return dict2
End Function
Public Shared Function jObjectToArray(json As String) As Generic.List(Of String)
Dim json2 = JObject.Parse(json)
Dim ar = json2.ToObject(Of Generic.List(Of Object))
Dim ar2 = ar.ConvertAll(Function(x) x.ToString)
Return ar2
End Function
The code sort of works.
I then did
Dim jsonar = jsonHelper.jObjectToDictionary(_jsonResult)(starttoken) 'works
Dim ar1 = jsonHelper.jObjectToArray(jsonar) 'doesn't work
Then I examine why jObjectToArray doesn't work and it leads to this one line code that I think should work but doesn't.
That's what I ask. If you can fix this problem of that one line code, I can figure the rest out.
The reason that JObject.Parse is failing is because your JSON represents an array of objects, not just a single object. You can tell because the JSON begins and ends with square brackets [ and ], as opposed to curly braces { and } which denote a single object. To parse an array, you need to use JArray.Parse. (Note you can also use JToken.Parse -- that will parse either a single object or an array.)
Dim json2 = Newtonsoft.Json.Linq.JArray.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")
Demo fiddle: https://dotnetfiddle.net/hZlc3m

Remove JSON object from array

I am using this to serialize my data to object in vb.net Newtonsoft.Json But what I want to do, is to delete object from my event array. The first one (index 0).
I know that can create a class and a list, but the data I get is changing from call to call.
Dim msg As String = Encoding.UTF8.GetString(message.Body)
Dim imgageInfo As Object = JsonConvert.DeserializeObject(Of Object)(msg)
MsgBox(imgageInfo("event")(0)("settings").ToString)
You could deserialize the object into a dictionary and make adjustments to the array from there.
JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
Maybe a sample of your json would help.