POST JSON string from Form in VB.NET - json

Here is my situation:
I have a form that is collecting a list of items in a textarea as a JSON Object.
The form textarea looks like this:
<textarea id="listItems">
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
</textarea>
I need to be able to parse that string and POST each item into a SQL Table.
ItemID | ItemName
-----------------
1 | apple
2 | orange
3 | banana
I don't think I have a good understanding of using the JavaScriptSerializer Class. I'm using VB.net
I don't have any server-side code yet but I know that I have to parse out the JSON string and then loop through it and then save each item.
Couldn't I just convert the JSON string into a DataTable and then loop through that temporary table?
Not sure. I'm trying to figure this out but some help would be useful.
Also I'm referencing a few SO posts to see if maybe I can figure this out
This one
This one

So expecting the following Json Object at the Server
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
you would be able to do this:
Public Function DoSomething()
Dim jsonObject = "[{""id"":""1"",""name"":""apple""},{""id"":""2"",""name"":""orange""},{""id"":""3"",""name"":""banana""}]"
Dim obj = New JavaScriptSerializer().Deserialize(Of TestObject())(jsonObject)
End Function
With this Model
Public Class TestObject
Public Property id As Integer
Public Property name As String
End Class
At runtime you will have an array of Objects in obj which you can then manipulate and fill into a DataTable or directly feed to the Database. Converting the Json into an Object is not the only option you have here but it is a convenient one.
Since you did not specify the context you are working in it is a little unclear what might be the best solution to your case. Maybe you want to do a little research on different Json Frameworks (for example Json.net) as well as Data-Handling with Databases so you get ideas about the how and when.

This was the best answer I found and I adjusted it to meet my needs.
I've also included the link to the duplicate POST that answered my question.
I'm also referencing another similar post which has a similar situation.
This is the link to the .Net Fiddle that demonstrates what I was looking for.
DEMO
How to deserialize JSON which can be an array or a single object
How to handle both a single item and an array for the same property using JSON.net

Related

How to deserialize json to class with missing fields

I'm following a tutorial where one of the tasks is to deserialize json using gson. I looked at several SO posts, but couldn't find one that addressed my issue. I get a string representation of an array in JSON whose fields look like below:
photoJsonArray
[{"id": "28857102437",
"owner":"9457266#N02",
"secret":"a5f02e005f",
"server":"857",
"farm":1,
"title":"",
"ispublic":1,
"isfriend":0,
"isfamily":0,
"url_s":"https:\/\/farm1.staticflickr.com\/857\/28857102437_a5f02e005f_m.jpg" ...and so on
I want to deserialize this list into a list of GalleryItem objects, which only includes the id,url_s and id fields from the JSON array.
I tried the following approach to converting the JSON string to a list of Gallery Item objects, but all the fields ended up with a null value.
Type photoType = new TypeToken<List<GalleryItem>>(){}.getType();
List<GalleryItem>galleryList = g.fromJson(photoJsonArray.toString(),photoType);
I would really appreciate if someone could point me in the right direction!
after some research I discovered that all the fields from the JSON string need to be declared in the class in order to deserialize the JSON into that class. Seems a bit overkill if all you need to use is a couple fields, but hope this helps.

Convert JSON to DataTable without using NewtonSoft library

So i am working on deserializing a JSON string into a vb.net DataTable.
Now my project runs on .NET3.5 framework and hence i have to fall back on the stock JavaScriptSerializer to do the work.
Is there a way to do this or does it need to done brute-force ?
Json.Net
You can use Json.Net (it Supports .Net 3.5), something like this:
JsonConvert.DeserializeObject(Of DataTable)(json)
This will be the easiest to implement but of course your JSON needs to be in precisely the correct format for that to work, and that's not always easy (or possible), especially with complex types such as DataTables.
Alternatively
Depending on your JSON structure (an example would be useful) It might be easier to convert from JSON to a list of simple objects and then iterate over those objects to populate the the DataTable.
i.e. Create a new class matching your JSON schema:
Class SimpleObject
Property Column1 As String
' etc.
End Class
Then loop through the list
Dim ListFromJson As List(Of SimpleObject) =JsonConvert.DeserializeObject(Of List(Of SimpleObject))(JsonString)
For Each item As SimpleObject In ListFromJson
' Create new row from each item in the list and add to the table
Next
In fact, with that approach, you might be able to do everything you need with the list itself, it will certainly be more efficient than a DataTable.
Without using Json.NET
If you really don't want to use Json.NET (which is your easiest option, and the industry standard) then you can use System.Runtime.Serialization.Json here is an example.
I am pretty sure that it wont automatically be able to convert to a DataTable though.
You will need to create a simple object as above to act as a middleman and loop through a list of those objects to put them in the DataTable.

VBA getting values from a collection?

I am very new to VBA and I can not figure out how to get values from a Collection.
This is my code:
Dim p As Object
Set p = JSON.parse(Response.Content)
Dim links As Object
Set links = p.Item("links")
In the debugger for "links" I see:
I am using this library to parse json : http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html
The part I have in json is:
"links":[
{
"rel":"next",
"href":"www.google.com"
}
]
How can I get the value of "rel" here?
Don't forget the bang operator, designed for collection access by key:
links(1)!rel
or:
links(1)![rel] 'When there are spaces or reserved words.
I will answer my own question:
links(1).Item("rel")
worked...
Regards..
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
You can see the full VBA code here

json deserialization vb.net

I need to deserialize this, which is encoded in JSON and I can not, I need it, anyone can help me?
[{"idReservation":2560,
"startDate":"30/09/2013 09:00",
"endDate":"30/09/2013 09:10",
"timeOut":"24/09/2013 16:02:23",
"idResource":1477,
"resourceDescription":"Profesional",
"players":
[{"idPlayer":283,
"idCustomer":2,
"name":"Ignacio",
"image":"/public/images/interface/customer/user.png",
"total":0}],
"anulable":true,
"name":"Ignacio",
"price":0,
"status":"Reservada",
"parententityname":"",
"idparententity":"",
"unixTime":1380524400},]
greetings and thank you very much
As #YuriyGalanter suggests Json.NET will do the job, it has great performance and avoids the problem you get when trying to serialise a javascript datetime object to .net datetime object.
The documentation provides an example of how to deserialise an object.
Expanding on Mr Shoubs' answer:
1) Download the Json.Net DLL per Mr Shoubs' answer.
2) Add a reference to this DLL in your Visual Studio Project.
3) Create a VB Reservation class that you want to end up with:
Public Class Reservation
Public Property idReservation() as Integer
Public Property startDate() as Date
...
End Class
Make the spelling and casing exactly as they are in the JSON object to keep things simple.
4) Declare an object of type Reservation and populate it with the JSON string you have - using the DeserializeObject method:
Dim obj As Reservation
obj = JsonConvert.DeserializeObject(Of Reservation)(yourJsonString)
obj should now contain the data you want.

Create a List-type view dynamically from a Json object in MVC3

I have a controller that access a WCF service which returns a Json object (collection). All rows are of same type, but at different calls the row stricture is different (the return object comes from a user-built sql query, executed with executeReader and serialized as Json
So I don't know the row structure upfront.
What I need is an easy way to pass this Json string to something which will generate a view of type list on the fly for it. Doesn't matter formatting, etc, just should be output easily as a table.
Does anyone knows how can I accomplish this?
Another option might be to have something that generate the view on the fly for a IEnumerable of anonymous objects (since using this I could convert the json to a list of anonymous)
EDIT
I found something that does pretty much what I need, except it display metadata about passed object.
It is preetyPrint.js, and I integrated it in my page as below:
In my controller I set the result json object to ViewBag.Result, and in the view I used this code:
<script src="#Url.Content("~/Scripts/prettyprint.js")" type="text/javascript"> </script>
<div id="resultGrid"></div>
<script>
var resultObject = #Html.Raw(ViewBag.Result);
var ppTable = prettyPrint(resultObject);
document.getElementById('resultGrid').appendChild(ppTable);
</script>
Does anyone knows such script that actually "dump" the data instead of metadata?
Thanks.
You should create a class to deserialize to if you know the properties of the row. Then use the JavaScriptSerializer class to deserialize to a list of your new class you created. Then you can take a look at the WebGrid class to output the HTML, or just manually iterate over the property metadata in your view.
Creating a custom class will provide you the ability to use metadata to control formatting or other display attributes of the output.
If you cannot create a custom class, you can always use Json.NET or the JavaScriptSerializer to deserialize to a list of dictionary objects or ExpandoObject / Dynamic's or something. Then you would have to manually write something to iterate the keys I think. The ModelMetadataProvider in MVC may be able to handle these allowing you to just iterate the properties in your view code.