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.
Related
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
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
I'm new using mySQL database. I have a class in Java that as an variable that is an array of strings.
I would like to save that array of strings on my database.
How can i represent my array of string in the mysql database?
thank you
I can think of some ways:
Serialize the object.
How does that work? First you need a table that can hold the class name and the object serialized. You need the class name for when you need to read the object from the database.
Sample code can be found here:
http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/,
and
http://www.java2s.com/Code/Java/Database-SQL-JDBC/HowtoserializedeserializeaJavaobjecttotheMySQLdatabase.htm
Sometimes all you need to serialize is not the object, but rather, the attributes of the object. In this case, you can use XML or JSON (for example).
In this case, create a String representation of your object and save it to the database as a text field.
You can map your object to one or more tables using any of the many ORM solutions, such as iBatis, Hibernate, etc.
http://java.dzone.com/articles/getting-started-ibatis-mybatis
http://hibernate.org/orm/
If what you need is to save some attributes of your object to the database then you can either use JDBC and just update the field, or use an ORM and create a POJO with only the attributes you'd like to save.
I'm trying to parse a grails parameter map to a Json String, and then back to a parameter map. (For saving html form entries with constraint-violations)
Everything is fine as long as there is no hasMany relationship in the parameter-map.
I'm using
fc.parameter = params as JSON
to save the params as JSON String.
Later I'm trying to rebuild the parameter map and create a new Domain-Object with it:
new Foo(JSON.parse(fc.parameter))
Everything is fine using only 1:1 relationships (states).
[states:2, listSize:50, name:TestFilter]
But when I try to rebuild a params-map with multi-select values (states)
[states:[1,2], listSize:50, name:TestFilter]
I'm getting this IllegalStateException:
Failed to convert property value of type org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.Set for property states; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [de.gotosec.approve.State] for property states[0]: no matching editors or conversion strategy found
I tried to use this, but without success:
JSON.use("deep") {
new Foo(JSON.parse(fc.parameter))
}
You can use JsonSlurper instead of the converters.JSON of grails, it maps JSON objects to Groovy Maps. I think this link also might help you.
Edit: Now, if the problem is binding the params map to your domain, you should try using bindData() method, like:
bindData(foo, params)
Note that this straightforward use is only if you're calling bindData inside a controller.
What seems to be happening in your case is that Grails is trying to bind a concrete type of List (ArrayList in the case of JsonSlurper and JSONArray in the case of converters.JSON) into a Set of properties (which is the default data structure for one-to-many associations). I would have to take a look at your code to confirm that. But, as you did substitute states: [1,2] for a method of your app, try another test to confirm this hypothesis. Change:
states:[1,2]
for
states:[1,2] as Set
If this is really the problem and not even bindData() works, take a look at this for a harder way to make it work using object marshalling and converters.JSON. I don't know if it's practical for you to use it in your project, but it sure works nicely ;)
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.