Automatic Conversion of JSON to Java Object - java

I was wondering if there is any way or library which allows the automatic conversion of json strings to java objects ?
i.e. similar functionality provided by Backbone for javascript.
I am fully aware you can do it step by step for each field using something like:
JSONObject json = new JSONObject(jsonString);
String body = json.get("body").toString;
However I have many json files to convert and manually typing out the code for ever object I need seems tedious. Is there anyway to do it autonomously ?
I.e. provide an object template which can be populated regardless of it's fields ?

Most frameworks that use ajax allow you to set a config that will do this for you.

MyClass a = Gson().fromJson(jsonString, MyClass.class)

Related

what is the best way to merge two java beans in RESTful API?

The scenario is simple:
UI call RESTful API to get an object tree, then UI change some data and call RESTful API to update it.
But for security or performance reason..., my RESTful API can NOT bring the whole object tree to the UI.
We have two choose for this purpose: creating an individual Java Bean for RESTful API or extend existing business Java Bean plus #JsonIgnore.
The second looks smarter because we re-use business class.
But Now we have a trouble: I need to merge the object from UI with the object from DB, otherwise I will lose some data.
But how do I know which piece of data will come from UI?
I know I can hard code to copy fields one by one.
But this way is dangerous.
I am asking for generic way to avoid hard code to copy fields.
I tried org.apache.commons.beanutils.BeanUtils, but it can't meet the requirement because it always overwrite target fields.
So I am thinking this way:
If the field in UI bean is not Null, then overwrite the value of the same name field in destination bean. but how do I handle if the field is some kind of primitive type like int which have default value 0?
I don't know if the field really carry an UI value 0 or just not comes back from UI.
I tried to convert primitive type to object type, but it still have troubles on boolean type, many java tools don’t support “ Boolean isValid(){…}” like BeanUtils. And this kind converting is dangerous on existing code.
I tried those code:
JacksonAnnotationIntrospector ai = new JacksonAnnotationIntrospector();
AnnotatedClass ac = AnnotatedClass.construct(MyClassDTO.class, ai, null);
String[] ignoredList = ai.findPropertiesToIgnore(ac);
for(String one: ignoredList){
System.out.println(one);
}
but ignoredList is always null. I am using Jackson 1.9.2
You could consider using JsonPatch. We use it and it works quite well. Of course it means you apply patches at the JSON level and not in the bean directly so if you need to support more than just JSON, it might be a problem.
Here's an implementation: https://github.com/fge/json-patch
I found the solution on Jackson:
MyBean defaults = objectMapper.readValue(defaultJson, MyBean.class);
ObjectReader updater = objectMapper.readerForUpdating(defaults);
MyBean merged = updater.readValue(overridesJson);
it comes from :
readerForUpdating
merging on Jackson

Java -parsing json into dynamic objects

I have a in-house api (that I can't edit) that parses json into a POJO.
The function looks like parse(String jsonString, Class jsonObj)
My problem is the the json string is dynamic. I don't always expect the same json object, so I want to avoid some ugly way of figuring out which json it is and pass in the correct class.
It would be nice to skip creating a bunch of classes to pass in.
How do I achieve this? I was thinking maybe reflection but not sure yet.

Using reflection to set property values where types are unknown

I am using reflection to set value object properties at runtime. If everything were a string, I may not be asking this question, but that's not the case. I have a web service that returns json and I want to use the json returned by the service to populate the object. I have an ArrayList of strings called alphabeticalKeys that contains sorted keys in the json string. Here is the code I am using to dynamically populate the object (user):
for(String fieldName : alphabeticalKeys){
Log.d("JSON:" + fieldName, json.getString(fieldName));
Field f = userClass.getDeclaredField(fieldName);
f.setAccessible(true);
f.set(user, jsonObject.get(fieldName));
}
In the json data set, there are strings, doubles and more. This is part of a factory class where the type of object being returned is unknown at compile time. Also, the json fields' data types may vary depending on the type of object needed.
The json output matches the field names in the returned object, so I am looking for a way to handle the different data types returned in the json output. Can somebody offer up a suggestion?
Thx! Vivian
There are libraries available to aid in setting property values using reflection, converting to the appropriate type if necessary. For example, Spring Framework's BeanWrapper and Apache Commons BeanUtils.
There are also json libraries that will handle mapping json to/from java objects. For example, Gson and Jackson. This may make it easier, especially if the json structure closely matches the java object structure.

Java String to JSON and then JSON to array

I have the following String code and I want to convert to json and iterate through items and put them into an arraylist in Java.
I also have a class called Users whith its attributes and getters/setters(id, nick, age, online, avatar)how should i do:
code:
//this is the real code
String a = "{"id":"1","nick":"jhon","age":20,"online":1,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"2","nick":"mike","age":45,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"3","nick":"carl","age":12,"online":1,"avatar":"http:\/\/www.example.com/image.jpeg"},{"id":"4","nick":"ana","age":22,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"}";
//this is what i want to do
String a = real code sample;
Json b = a.toJson; // something like this
Arraylist<User> list = new Arraylist<User>();
for each b{
list.add( new user(b.getId(),b.getNick()....));
}
i want to do something like that and of course the code is an example and here it's not well written.
You may prefer to use Gson library which has good documentation for how to use. You can easly parse objects to JSON and JSON to object. So it may be a better alternative for your own parser.
It also supports Arrays and Collections.
I think you need to validate you array first on JSONLINT
Jackson is quite nice for this sort of thing - I've been using it for some time with no problems. I've heard nice things about Gson as well, but had no reason to switch from Jackson. Xstream also can work with Json.
Instead of working with a special "JSON" object, Jackson (and I believe Gson as well) stuff the JSON values into a POJO. You use the annotations to customize how the values are read and written.
FWIW, JSON processing is easy with a library like this, but also something you don't want to do much - it's relatively expensive in terms of CPU. It's not that the libs are slow - that kind of text processing is a lot of work.

How to pass an array of objects from javascript to Java

Hello Im trying to pass an array of objects from javascript to java , but how can this be done..??
I've found in some posts that they do this using a hidden input. Is this the only way?
I'm a bit confused. Please tell me what do I need to do to pass my array to the server? and which javascript files and jars do I need to add?
Thanks in advance.
You seem to want a completely baked-in solution. Not sure I can provide that, but here's what I'd do.
Indeed use a hidden input field in a form, where the value of the field is a valid JSON string. Send the form to your server, and in your servlet use a JSON Java library to parse the JSON string.
Here json-lib, gson or Jackson would do. In your case, I'd say json-lib would seem the easiest to use.
To generate the JSON string on the client-side, either use a framework or custom solution. For instance, jQuery has a serialize() function to serialize a form's fields to a JSON object directly, which you can then convert to string. Other frameworks provide similar functions.
To learn more about JSON, be sure to read the JSON Wikipedia entry and to visit the official JSON page (which also gives you a Java implementation of the JSON data-interchange format, though maybe not the most efficient one for processing a lot of data). To make sure your generated JSON is valid, you can use JSONLint.
If the objects are simple enough, you can encode your array as a JSON string. Java has libraries to encode and decode JSON.

Categories