Convert JSON String to Java object for easy use in JSP - java

Is their an easy way or library to convert a JSON String to a Java object such that I can easily reference the elements in a JSP page? I think Map's can be referenced with simple dot notation in JSP pages, so JSON -> Map object should work?
UPDATE: Thank you for all the JSON Java libraries. In particular, I'm looking for a library that makes it easy for consumption in JSP pages. That means either the Java object created has appropriate getter methods corresponding to names of JSON nodes (is this possible?) or there's some other mechanism which makes it easy like the Map object.

Use Jackson.
Updated:
If you have an arbitrary json string Jackson can return a map object to access the properties values.
Here a simple example.
#Test
public void testJsonMap() throws JsonParseException, JsonMappingException, IOException {
String json = "{\"number\":\"8119123912\",\"msg\":\"Hello world\"}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
System.out.println("number:" + map.get("number") + " msg:" + map.get("msg"));
}
Output:
number:8119123912 msg:Hello world

Try GSON, here is a tutorial.

This library should do what you want: http://www.json.org/java/

DWR can be used for this purpose DWR - Easy Ajax for JAVA .
Lets consider this java class.
class Employee
{
int id;
String eName;
// setters and getters
}
In javascript JSON object
var employee = {
id : null,
name : null
};
This is the call to java method from javascript function.
EmployeeUtil.getRow(employee,dwrData);
In getRow() of EmployeeUtil class, return type of method will be Employee.
Employee getRow();
So using the setters of Employee set the data.
dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned which is Employee bean will be in callback function.
Just initialize this in javascript JSON object.
Now the JSON object can be parsed and displayed in jsp.
This example shows Dynamically Editing a Table
Hope this helps ....

Related

Get value from object by key in java

I am getting object in the response of entityManager.find method.
and i want to get values from that object by passing key. but i din't get any success.
For example :-
my entity :-
#entity
class Test (){
public Long id;
public String name ;
public String descr;
}
and i am getting object in the response of below code.
`Object obj=`entitymanager.find(classname,id);
Note :- Instead of object i can't use entity's object directly because input class name can be dynamically pass that's why i am taking response in Object.
Now i want to get value from object by passing key
something like that obj.getvalue("id");
I tried below things to make it done :-
Map<String, Object> user = (Map<String, Object>)obj;
Used json simple parser to parse it.
JSONParser parser = new JSONParser();
JSONObject jsonObject =parser.parse(obj.toString());
But din't get any success.
Please help me out.
I'm a little unsure of what you're asking... but as long as "name" is a primary key you can call
Test obj = entitymanager.find(Test.class, name);
Object obj=entitymanager.find(classname,id);
In the above line what is the type of "classname".
Since your question does not mention the type. I assume its of type Object.
You should do something like
Object obj=entitymanager.find(classname.getClass(),id);

How can I deserialize a list of enums using Jackson JSON?

I'm working on a configuration system. I'd like to be able to load config values from a JSON file and have them "automagically" convert to the Java type I need. I'm using Jackson for the JSON parsing. For primitive types like floats and strings, it's no big deal, but I'm running into a snag with enums.
Let's say I have the following enum:
public enum SystemMode
{
#JsonProperty("Mode1")
MODE1("Mode1"),
#JsonProperty("Mode2")
MODE2("Mode2"),
#JsonProperty("Mode3")
MODE3("Mode3");
private final String name;
private SystemMode(String name)
{
this.name = name;
}
#Override
#JsonValue
public String toString()
{
return this.name;
}
}
Now, let's say I want to represent a list of values of this enum for a given config variable using the following JSON representation:
{
"Project" : "TEST",
"System" : {
"ValidModes" : ["Mode1", "Mode2"]
}
}
And I'd like to be able to do something like the following:
ArrayList<SystemMode> validModes = (ArrayList<SystemMode>) configurator.getConfigValue("/System/ValidModes");
For reference, my configurator class's getConfigValue method is essentially a thin wrapper over the Jackson JSON parsing:
public Object getConfigValue(String JSON_String)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(JSON_String);
return objectMapper.convertValue(node, Object.class);
}
(The real method has some exception checking that has been omitted for clarity).
Now, when I call the above, Jackson correctly deduces that I want an ArrayList and fills it. However, instead of getting an ArrayList of SystemMode enums, I get an ArrayList of Strings and immediately throw an exception when I attempt to use the list. I have tried several different ways of representing the data to no avail. It seems no matter what I try, Jackson wants to return a list of strings instead of a list of enums.
So my question is this:
How can I make Jackson (version 2.9.4) JSON properly deserialize a list of enum values in a way that is compatible with my single "Object getConfigValue()" method?
The following will provide the correct binding for your enum.
public List<SystemMode> getConfigValue(String path)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(path);
return objectMapper.convertValue(node, new TypeReference<List<SystemMode>>(){});
}
The second option is to convert the list of String yourself, for example:
List<SystemMode> result = jsonResult.stream().map(SystemMode::valueOf).collect(Collectors.toList());
Third option:
public <T>List<T> getConfigValue(String path, Class<T> type)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(path);
CollectionType toType =
objectMapper.getTypeFactory().constructCollectionType(List.class, type);
return objectMapper.convertValue(node, toType);
}

How to create an object of specific Java class from JSON object depending on it's fields values?

I'm trying to deserialize objects from JSON file.
I have abstract class Car, which is extended by Minibus and Minivan classes.
I determine the exact class by values of maxPassengers and trunkSize fields.
I need to create a MinibusCar or MinivanCar object when I deserialize based on the parameters in JSON. What is the most efficient way to do that? Please advice.
There is not enough information here. Can you show us an example of this json file?
In general, you can use Jackson package:
// Serialize into JSONObject
JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
// Get your value from it, for example:
int maxPassengers = json.get("maxPassengers");
// Init your object mapper
ObjectMapper mapper = new ObjectMapper();
// Based on this value, create your object
Car car; // Using polymorphism (you can also read about Factory design pattern)
if (maxPassengers > 10){
car = mapper.readValue(jsonTxt, MinibusCar.class);
} else {
car = mapper.readValue(jsonTxt, MinivanCar.class);
}
But this solution isn't perfect until you will show us the classes (three of them) and some json example file.
Good luck!

Getter (accessor) based serialization (json or xml)

I need to serialize a couple of objects in my Android app and send them to web service.
The model classes for objects have various int fields which need to be converted into meaningful string representations from various arrays before sending to web service.
So, I am assuming that easiest way will be to use gson or xstream (JSON or XML - anything is fine) but with following method:
- I'll mark all existing int fields as transient and exclude them from serialization
- I'll create new get method per field. The get method will read value of corresponding integer and return its string representation.
But in either of 2 libraries - gson or xstream, I am unable to find way to serialize based on getters instead of fields. Please suggest.
And yes, I DO NOT need to deserialize the data back.
I think you need a wrapper class.
Consider this:
public class Blammy
{
private int gender;
... imagine the rest of the class.
}
public class BlammyWrapper
{
private String gender;
public BlammyWrapper(final Blammy blammy)
{
if (blammy.gender == 1)
{
gender = "Its a Boy";
}
else if (blammy.gender == 2)
{
gender = "girl";
}
else // always check your boundary conditions.
{
throw new InvalidArgumentException("Naughty blammy; unrecognized gender value");
}
public String gender()
{
return gender;
}
}
Ok, finally, I followed this approach:
1. Removed all resource arrays from my app code
2. Added enums with toString for each current array
3. Changed all int properties to be of corresponding enum type
4. Used XStream
5. Added a custom convertor for XStream for generic enum types where if it finds any property of type enum, then it will marshal it using toString method.
Thanks for all support btw. All your answers and comments atleast made me clear that my current code architecture needed drastic improvement.

Mapping JSON to Java objects with different keywords

My company has a webserver API that provides search results in JSON format. I'm responsible for developing an Android app that consumes that API, and I have made some classes that model the objects in the JSON responses.
For the sake of habit and my own preference, I use to write my code in English only. However, most of the JSON keys are not in English. This way, I cannot readily use GSON to convert the JSON strings into Java Objects -- at least that is what I think.
I was wondering if there is any way to reference just once per class the connection between the JSON key and their corresponding instance variables in the code. In a way that after referenced, I could simply instantiate objects from JSON and create JSON strings from objects.
Is that possible?
Example:
// Java code
class Model {
String name;
Integer age;
}
// JSON with keys in Portuguese
{
"nome" : "Mark M.", # Key "nome" matches variable "name"
"idade" : 30 # Key "idade" matches variable "age"
}
Use the #SerializedName annotation.
Here is an example of how this annotation is meant to be used:
public class SomeClassWithFields {
#SerializedName("name") private final String someField;
private final String someOtherField;
public SomeClassWithFields(String a, String b) {
this.someField = a;
this.someOtherField = b;
}
}
The following shows the output that is generated when serializing an instance of the above example class:
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(objectToSerialize);
System.out.println(jsonRepresentation);
===== OUTPUT =====
{"name":"a","someOtherField":"b"}
Source: SerializedName Javadocs

Categories