Possibility of using Generic function to convert any Java Object to JSON - java

I would like to know if it is possible to convert any Java object to JSON object. Currently I have the following code.
JSONArray data = new JSONArray();
for (User user : users) {
JSONArray row = new JSONArray();
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
The current issue is different object (e.g. User and Admin) will have different property, thus the above code will work for other object. I am thinking of putting a similar code in my GenericHibernateDAO in order to automatically convert any list into a json list.

You can serialize your java object to json object. There are n number of library is available ex gson, jettyson, flexjson etc.
GSON example -
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

Here i exemplify the way of converting POJO to json using jackson
create your pojo : User user = new User();
you can set or get values to/from user
create ObjectMapper : ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);// object to json

Related

Convert JSON String to JSON object to get Values

I am getting a JSON string and want to print Name values on the console via JSP. Can someone suggest how to do it?
String AllCustomLockingCriterias = '{"TemplateArray":[{"Id":16,"Name":"Machine","type":"PM"},
{"Id":17,"Name":"Ethernet","type":"PM"},
{"Id":18,"Name":"Hard Disk","type":"PM"}]}';
Output I need:
Machine
Ethernet
Hard Disc
I want to start a loop and my output will be:
Machine
Ethernet
Hard Disc
use Gson jar package(produced by google.com) , FastJson(produced by alibaba.com) or jackson to serialize or deserialize the json string and the Class object.One jar package is enough.
use maven pom dependency/gradle config to add the gson to your project or add the gson jar into your lib folder directly,it is all up to you, maven is preferred.
define the Java Class field member,with the meta info from your json string,such as 'id','name','type'.The Java Class can be named 'Template'(do not forget to implement the java Serializable interface).
code example:
Gson gson = new Gson();
TypeToken typeToken = new TypeToken<List<Template>>() {};
Type type = typeToken.getType();
List<Template> templates = gson.fromJson(json, type);
return the templates list to the front jsp page within the jsp page scope.
if you user springMVC framework,you can add a model param to the method params,
#RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(Model model){
model.addAttribute("templates",templates);
return "jspFileName";
}
for jsp site,you can use jsp EL Express to show the list
<c:forEach items="${templates}" var = "template">
${template.name}
</c:forEach>
the last but the most easy method is ,you can pass the json string to the jsp page.on the other words,do not need to serialize the json string to class,just pass the string to the jsp with the model attribute provided by springMVC or even the basic Servlet.And then use the javascript method to handle the json string.for example,
var obj = JSON.parse(json);
var array = obj.TemplateArray;
array.foreach(function(item) {
console.log(item.name);
});
"fasterxml" or "jackson" has Java library that is able to transform your JSON string to a TreeNode. You can then access various fields.
#Test
public void test() throws IOException {
String AllCustomLockingCriterias = "{\"TemplateArray\":[{\"Id\":16,\"Name\":\"Machine\",\"type\":\"PM\"},\n" +
" {\"Id\":17,\"Name\":\"Ethernet\",\"type\":\"PM\"},\n" +
" {\"Id\":18,\"Name\":\"Hard Disk\",\"type\":\"PM\"}]}";
//create mapper to map JSON string to handy Java object
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readValue(AllCustomLockingCriterias,JsonNode.class);
//fetch value that has field name "TemplateArray"
JsonNode templateArray = rootNode.get("TemplateArray");
//loop over the values in the TemplateArray and extract Name, if present.
for(JsonNode subNode : templateArray){
if(subNode.has("Name")){
System.out.println(subNode.get("Name"));
}
}
}
Use JsonNode with JPointer.
Example:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(
"{\"TemplateArray\":[{\"Id\":16,\"Name\":\"Machine\",\"type\":\"PM\"}, {\"Id\":17,\"Name\":\"Ethernet\",\"type\":\"PM\"},{\"Id\":18,\"Name\":\"Hard Disk\",\"type\":\"PM\"}]}",
JsonNode.class);
node.at("/TemplateArray").forEach(a -> System.out.println(a.at("/Name")));
Prints:
"Machine"
"Ethernet"
"Hard Disk"

How to convert JSON to HashMap and compare them?

I have a json stored in a DB like this,
"supported_iso_codes":[
{
"EUR": "978",
"USD": "840"
}
],
To access this in my app code, I do something like this..
getISOProfileDB.getSupportedISOCodes();
I have a string which the user inputs(provides input string like EUR, USD,etc). How can I convert the above json to a HashMap and compare it with another string? What I am trying to achieve is,
Compare Key part of json to user input string(EUR).
If both of them match,
Parse the value part of json and store it in a variable.
Below is what I'm trying to achieve,
tran.setCurrency(hashMapOfJson.get(currencyString));
Use Gson :
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
And then :
Map<String, Object> supported_iso_codes = new Gson().fromJson(getISOProfileDB.getSupportedISOCodes(), new TypeToken<HashMap<String, Object>>() {}.getType());
You can do something like this
Gson gson = new Gson();
Type type = new TypeToken<List<Map<String, String>>>(){}.getType();
final ArrayList<HashMap<String,String>> isoCodesMapList = gson.fromJson(data, type);
System.out.println(arrayList);
then for getting the user selected currency you can do
isoCodesMapList.get(userSelectedCurrency);
Hope this helps:)
You should consider using JSONObject (Jsonobject.org) or Gson.

Java: Json schema generator (for string orJSONObject)

Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.
looks like there isn't. I had to write my own generator.
Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.
You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);

Get JSON values to form an Object

Using GSON :
Gson gson = new Gson();
String json = gson.toJson(response);
System.out.println(json);
I receive the following JSON representation of a User:
"{\"userID\":\"user2\",\"firstName\":\"Maria\",\"lastName\":\"Silva\",\"birthDate\":\"Ago 1, 2012\",\"gender\":\"Female\"}"
Now, I want to get those values to construct a User object (doing User.setuserID, userObj.setFirstName, ... )
How can I get the correspond values to set the User values?
Gson will do that for you. You need not worry about it. That's the power of Gson.
User object = gson.fromJson(jsonString, User.class); // Fully populated User object.

Java parse JSON String to array or objectlist

I'm not very familiar with Java, but got the job to reverse the following JSON-Output to a JAVA object-structure:
Sample:
{"MS":["FRA",56.12,11.67,"BUY"],"DELL":["MUC",54.76,9.07,"SELL"]}
Does someone know, how to build the Arrays / Objetcs and the code to read the strings with Java? JSON or GSON codesamples are welcome.
Thanks!
You could try something like:
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> map = new HashMap<String, String>();
map = gson.fromJson( json, type );
Where "json" is the json string you defined.
Jackson library is most commonly used to parse JSON in Java. Forget about regular expressions and parsing by hand, this is more complicated than you might think. It all boils down to:
String json = "{\"MS\":[\"FRA\",56.12,11.67,\"BUY\"],\"DELL\":[\"MUC\",54.76,9.07,\"SELL\"]}";
ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(json, Map.class);
You can also map directly to Java beans.

Categories

Resources