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'
Related
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"
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);
i got problems when i try to parse json with ObjectMapper and in the json there is an number that look like mate
json
{ "_id" : 290365351583, "my_number" : 1.5638694276102368E8 }
my code
ObjectMapper objectMapper= new ObjectMapper();
DBobject obj = ;\\the json when i select it from mongo db
String data = JSONSerializers.getStrict().serialize(obj);
JsonNode = objectMapper.readTree(data);
when i run this code i got ERROR "Non-standart token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"
You can use this maven dependency : http://mvnrepository.com/artifact/org.json/json/20160212
It's very simple to understated and use.
ex:
JSONObject obj = "YOUR_JSON_STRING";
String result = obj.getString("YOUR_STRING_KEY");
There you can use alot of methods like: getInt(), getDouble(), getBoolean() etc.
Useful examples are there : http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
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.
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