Jackson: can not get String value from JsonNode - java

I have a root-JsonNode
JsonNode payloadNode;
with the following textValue (log.warn("PAYLOAD_NODE" + payloadNode.textValue());):
{"id":0,"uid":""}
But when I,m trying to get String-value from this node:
JsonNode idNode = payloadNode.get("id");
I receive null

Have a look at this.
Method to use for accessing String values. Does NOT do any conversions for non-String value nodes; for non-String values (ones for which isTextual() returns false) null will be returned. For String values, null is never returned (but empty Strings may be)
As it is a text value it is just a string that has no field "id".
So if you have something like this:
String s = "{\"id\":0,\"uid\":\"\"}";
payloadNode = om.valueToTree(s);
you would get such a log output if your JsonNode was just a string as in my example. You need to read your possible string as a json tree so like:
payloadNode = om.readTree(s);
Doing this will give you "0" for id and null for textValue().

Related

How to access the value from a key-value pair in a jsonnode

I have got a JsonNode like the below
"{"Pink":["#000000"],"Red":["#000000"],"Blue":["#000000"],"Orange":["#000000"]}"
and I am trying to get the value for Pink for e.g like this
jsonNode.get("Pink").asText()
But this isn't working - is there another way that I can access these values through Java?
It looks like your problem here is that "Pink" is an array and not a string. The solution here is to either remove the square brackets, or if that is not possible, the following should give you the expected result:
jsonNode.get("Pink").get(0).asText()
This method will help you to traverse JsonNode
public void getColorCode() throws JsonProcessingException {
String color = "{\"Pink\":[\"#000000\"],\"Red\":[\"#000000\"],\"Blue\":[\"#000000\"],\"Orange\":[\"#000000\"]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(color);
for (JsonNode colorCode : node.get("Pink")){
System.out.println(colorCode);
}
}

Unknown depth nested maps check key existence and get value

I have a hashmap of the following structure:-
mymap = {a:{b:{c:{d:{e}}}}
How do I check the existance of key "d" in hashmap mymap in the simplest way?
Is there any Java8 features that might come in handy here?
mymap.get( "a" )).get( "b" )..;
is not going to work because I don't know the level in which d is nested.
How do I check if d is present in the map, and get its value without this trailing call? Thanks in advance.
I have recently had a similar problem and managed to come up with a solution which works with any JSON depths.
It is a solution which transforms the String into a JsonNode Object and then tries to find the parent value of a given fieldName (in this case 'd'). The result returning something which is not null, will tell you if the value exists or not.
ObjectMapper mapper = new ObjectMapper();
String myMapJson = "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":\"\"}}}}"
JsonNode data = mapper.readTree(myMapJson);
if (((ObjectNode)data.findParent("d")) != null) {
// Do something if value is found
} else {
// Do something if value is not found
}
Hope this helps..
You can use the FasterXML-Jackson library, which gives you the simplicty of traversing over nesed json.
For example:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
String myMapJson = "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":\"\"}}}}"
JsonNode data = mapper.readTree(myMapJson);
boolean hasKey = data.has("d");
Or, if you already have the object as Map you can write it as json and then load it the same way above:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
String jsonData = mapper.writeValueAsString(myMapObject);
JsonNode data = mapper.readTree(jsonData);
boolean hasKey = data.has("d");
if (hasKey) {
JsonNode result = data.findValue("d");
}

Java - parse string to Json and convert all number values to int

When I parse string:
{"action":"duelInvite","id":"1","matchType":"3"}
to JsonObject in this case all values are strings, but how to create JsonObject, that maps id and matchType to int? Do I have to do it manually, when getting those values? It's easier to .getInt("id") rather than Integer.parseInt(.getString("id"))
When you create a JSON Object from a string, all values become strings within the JSON Object. So you're right, you'll have to do it manually. But instead of parsing every time you want to get the values, just do it once when you create the object.
//create your object from the string
jsonObject = new JSONObject(string);
//set the key "id" to the integer value of the String at key "id"
jsonObject.put("id", Integer.parseInt(jsonObject.get("id")));
//set the key "matchType" to the integer value of the String at key "matchType"
jsonObject.put("matchType", Integer.parseInt(jsonObject.get("matchType")));

converting string into json object

I am getting a string like String s = "abc:xyz". Is there any direct method to convert it into JsonObject having abc as key and xyz as value.
I know there a way by converting string into String s = "{\"abc\":\"xyz\"}" and then I can use JSONObject j =(JSONObject) new JSONParser().parse(s); But I have too large list of string to convert into json object. So i don't want to preprocess to convert into quoted string.
And one more way to split string on : . But i want to know any parser method which convert directly into object. So that i does not have to split. It is also a kind of preprocessing.
If there is any way to convert by passing string to method. please suggest.
It sounds like you just want:
String[] bits = s.split(":");
if (bits.length() != 2) {
// Throw an exception or whatever you want
}
JSONObject json = new JSONObject();
json.put(bits[0], bits[1]);
Split the string on :; use the parts to make your object.

Json array in Java

I have a JSON array:
**
**
{
"Required" : true,
"Validation" : {
"MaxChars" : "40"
"MinChars" : "10"
}
}
**
**
The code now:
JSONObject formField = formListAdapter.formArray.getJSONObject(i);
if(formField.has("Required") && formField.getBoolean("Required") == true){
}
With the aforementioned code, I can check if in the JSON there is a field with the name "Required" and if this is true. But how can check if the Validation has an attribute inside? and how can I check the name and the value of it?
I.e. how can I check the number of the MaxChars or MinChars?
You can use JSONObject#getJSONObject to get the JSONObject corresponding to the key and then you can perform the same operations to get the values from the key.
JSONObject validationObject = formField.getJSONObject("Validation");
or you can use a better way, Use jackson
JSONObject validationObject = jsonObject.getJSONObject("Validation");
if (validationObject.has("MaxChars")) {
int maxChars = validationObject.getInt("MaxChars");
...
}
// same for MinChars
To get the attribute names for validationObject, you can use:
String[] names = JSONObject.getNames(validationObject);
You have to check the values of the "Validiation" object.
I never had worked with json.org but i belive you can create a new JSONObject from it and read the values like you work with the object in the array.
You want JSONObject.getJSONObject(String field) to get the enclosed JSON object.

Categories

Resources