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/
Related
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'
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"
New to java here coming from .NET and having some issue with parsing json. I need to be able to verify that a node exists and that the value is also not null before attempting to try and retrieve the value. I tried the following but not sure if this is the best approach.
ObjectMapper mapper = new ObjectMapper();
JsonNode messageNode = mapper.readTree(post);
id = messageNode.path("id").asText();
author = messageNode.path("actor").get("displayName").asText();
authorId = messageNode.path("actor").get("id").asText();
authorLink = messageNode.path("actor").get("link").asText();
if (! messageNode.path("actor").get("link").isMissingNode()) {
imageLink = messageNode.path("actor").get("link").asText();
}
pauthor = messageNode.path("actor").get("preferredUsername").asText();
Do I just use this for each field but how do I also check for null value?
Sounds like you should benefit from using JsonNode.has(...) and JsonNode.hasNotNull(...) methods.
I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need
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