Convert JSON String to JSON object to get Values - java

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"

Related

Get Json Value from text

I have a REST response, which contains text and JSON value. I need to get uniqueId from JSON value, what will be the best way?
My JSON is very big, but looks like this:
paymentResponse = Published your custom Transaction json to topic env_txn_endtoend_01 Final json: {"txnId":null, "envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534" etc...}}
How can I get this uniqueId value = 234234_2344432_23442?
There are many libraries to help with Json Serialization and Deserialization. Jackson Object Mapper is one of the most popular ones.
The code would be something like this. To begin with you would need Java Pojo which represents your json Object e.g. let's consider this example from this tutorial, where you can create a Car Java Object from a Car json string.
ObjectMapper objectMapper = new ObjectMapper();
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class); // you should have a Car Class(Pojo) with color, and type attributes
Final json: {"txnId":null,
"envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534"
etc...}}
How can i get this uniqueId value = 234234_2344432_23442
You could do something like this:
import groovy.json.JsonSlurper
...
String jsonString = '{"txnId":null, "envelope":{"uniqueId":"234234_2344432_23442","rootID":"34534554534"}}'
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)
def envelope = json.envelope
String rootId = envelope.rootID
assert rootId == '34534554534'
String uniqueId = envelope.uniqueId
assert uniqueId == '234234_2344432_23442'

Parse querystrings of a request as JSON

I'm going to receive requests with a JSON object passed as querystring which will no longer have a JSON structure, it will be something like this:
http:/mysite/api/doSomething?name=name&address=address...
I need to store it as a String following a JSON structure, the problem is that the original JSON object passed as querystring may have attributes that are collections and I can't figure out a way to parse it back correctly.
Is there a Java function or a library to achieve this easily?
I assume you are using spring mvc/jersey in controller. In that case you can do something like this
#RequestMapping(value = "/mysite/api/doSomething", method = RequestMethod.GET)
public String search(
#RequestParam Map<String,String> allRequestParams) {
JSONObject js = new JSONObject();
for (Map.Entry<String,String> entry : allRequestParams.entrySet()){
js.put(entry.getKey(), entry.getValue());
}
String jsonString = js.toString();
}
Basically get all the queryparam and construct JSONObjcet, JACKSON library will not be of much use here.

How to convert json formated java string to json object in controller

All examples of converting string to json are of javascript. mine is java class. So, i have a simple java string but formated in json. now i have recieved that from jquery post. now i have to convert that string into json object so that i can access the specific fields.
controller class
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public void storeData(#RequestParam(value = "temp_str", required = false) String j_str, HttpServletRequest request) {
// do the conversion and extraction of data from "j_str"
}
j_str variable is recieveing this string
{"temp_data":[{"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}]}
http://www.javacreed.com/simple-gson-example/
Gson gson = new GsonBuilder().create();
Person p = gson.fromJson("your json string", Person.class);
System.out.println(p);
you can use that libary to manage json objectos its very cool
the Person.class is a java bean must have all properties you have in your string
If your Json string is extremely simple, you can just use:
JSONObject jobj=new JSONObject(j_str);
Now you can access the JSON elements by:
JSONArray jarr=jobj.getJSONArray('temp_data');
JSONObject jarr1=jarr.get(0); // will contain {"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}
Now you can further access jarr1 similar to jobj.

nameValuePair key added in new JSONObject

When I am building a json object from string it is appended with a root key "nameValuePairs".
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
results to
{"nameValuePairs":{"b":"{}","c":"{}","a":"{}"}}
Why?
Any way to prevent that?
Btw, I am using the string json to represent the actual json which I will use later.
First of all your json is syntactically correct but I guess you wished to represent objects as values, in your case the curly brackets are evaluated as simple strings:
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
using a json like this instead will produce values as objects:
String curStr = "{\"e\": {}, \"f\": {}, \"g\": {}}";
JSONObject oldObj = new JSONObject(curStr);
Anyway, I've tried to create that JSONObject and then print a toString of it, and it will simply print the json, without any accessory name.
As you find out in the comment the problem was given by Gson, that will evaluate the JSONObject as a map. I've tried a little example and I've got "map" as field. Probably I've tried a different version of Gson.
Gson gson = new Gson();
String jsonStr = gson.toJson(oldObj);
result: {"map":{"f":"{}","g":"{}","e":"{}"}}
If you want to create a custom object and deserialize a json with Gson create a class with those properties and use the fromJson(String json, Class clazz) method
public class Test {
private String e;
private String f;
private String g;
}
and
Gson gson = new Gson();
Test myTestObj = gson.fromJson(curStr, Test.class);
Hope this will help you. :)
You can try jsonStringer instead.
Something like below code:
JSONStringer jObject = new JSONStringer()
.object()
.key("UserName").value(userNameValue)
.key("Name").value(nameValue)
.key("EmailId").value(emailIdValue)
.key("CountryId").value(contryIdValue)
.key("CountryName").value("") // It should be blank As Spanish Name is not set if User have App in Spanish
.key("State").value(stateValue)
.key("City").value(cityValue)
.key("ImageByteArray").value(imageBytes)
.endObject();
UPDATE
I have just use your code in my App and check it.
Its showing me the result as we have formed.
Result i am getting is:
{
"f": "{}",
"g": "{}",
"e": "{}"
}
Please check your packages you are importing.
For your reference i am importing below class to represent json object.
import org.json.JSONException;
import org.json.JSONObject;
Just import above class and see the result.
Let me know if you still have any query.

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

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

Categories

Resources