Java Rest Template - java

ResponseEntity<BaseDto> entity = restTemplate.getForEntity("/get/code/IN", BaseDto.class);
System.out.println("entity : " + entity);
System.out.println("entity.getBody() : " + entity.getBody());
System.out.println(entity.getBody().getResponseObject());
As per above rest am getting below format:
{
systemTrack=
{
createUser=admin,
createDate=2016-03-01 18:11:17,
lastUpdatedUser=admin,
lastUpdatedDate=2016-03-01 18:11:17
},
countryCode=IN, countryName=INDIA
}
How to get the values from this format?

Maybe I was unclear with my question, but i got a solution through debug mode.
It was a format which is in Linked hash map ,so what I did was I just wrote below code for json conversion of LinkedHashMap.
LinkedHashMap m = (LinkedHashMap) object;
JSONObject jsonObject = new JSONObject(m);(package of org.json.JSONObject)
and then i assigned to custom class object using
Gson gson = new Gson();
String jsonString = jsonObject.toString();
Object obj = gson.fromJson(jsonString, type);

Related

How to retrieve json array elements from JSON object in Java?

JSONObject firstObject = (JSONObject) jsonParser.parse(new FileReader(firstNamesPath));
I have this JSONObject, and I want to be able to access elements in the array inside of it. The object opens successfully, I just don't know how to access the array called "firstNames". It is in a file, and the object looks like this.
{
"firstNames": [
"Aaron",
"Abigail",
"Albert",
"Bob"
]
}
Edit: I am using org.json.simple.JSONObject . If this is not recommended, I am more than willing to change it.
There are several ways to retrieve the json array value:
Assume we have a jsonString
jsonString = "{\n" + " \"firstNames\": [ \n" + " \"Aaron\",\n" + " \"Abigail\",\n" + " \"Albert\",\n" + " \"Bob\"\n" + " ]\n" + "}";
(since many classes share similar names, I am using the groupId and artifactId for distinction.)
Simple cases: use generic JSONObjects and JSONArrays.
json-simple (which OP is using) json-simple website, maven :
org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser();
org.json.simple.JSONObject firstObject = (org.json.simple.JSONObject) jsonParser.parse(jsonString);
org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) firstObject.get("firstNames");
System.out.println(jsonArray);
JSON in Java (mentioned in adendrata's answer): JSON-Java doc, maven
org.json.JSONObject secondObject = new org.json.JSONObject(jsonString);
org.json.JSONArray jsonArray2 = secondObject.getJSONArray("firstNames");
System.out.println(jsonArray2);
gson: Gson, maven
com.google.gson.JsonObject thirdObject = com.google.gson.JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(thirdObject.get("firstNames").getAsJsonArray());
For more complicated use cases, if you'd like to define your own class, and want to deserialize JSON string to your class, then you can use Gson or Jackson:
// Create your own class:
/*
public class YourOwnClass {
private List<String> firstNames;
public List<String> getFirstNames() {
return firstNames;
}
}
*/
Gson gson = new Gson();
YourOwnClass customObject1 = gson.fromJson(jsonString, YourOwnClass.class);
System.out.println(customObject1.getFirstNames());
ObjectMapper mapper = new ObjectMapper();
YourOwnClass customObject2 = mapper.readValue(jsonString, YourOwnClass.class);
System.out.println(customObject2.getFirstNames());
you can use JSONArray to get array type of Json and looping to access each index
example:
JSONArray array = firstObject.getJSONArray("firstNames");
for (int i = 0; i < array.length(); i++) {
System.out.println("Hello i'm " + array.get(i));
}
Try to use this : com.alibaba.fastjson.JSONObject, and here's the dependency:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
Then you can directly use the getJSONArray method the answer shown above.

JsonNode Null JsonArray Parser

I am having a JsonNode response ( unirest ) which I want to parse using JSON Parser.
Now, let's say the structure is somewhat like this :
{
"expand" : "names",
"customfield_1" : null,
"customfield_2" : [ { "email":"123#gmail.com"},{...}]
}
So, the problem is that customfield_1 is a JsonArray and sometimes it can be null.
So, as soon as I use
JSONArray myArr = myObj.getJSONArray("customfield_1")
I get the following error:
org.json.JSONException: JSONObject["customfield_1"] is not a JSONArray.
I tried to change to JsonObject and JsonString but they also didn't help. How to avoid it ?
You can explicitly check if the field is null before getting the array:
JSONArray myArr = myObj.isNull("field") ? null : myObj.getJSONArray("field");
Complete example with your data:
String jsonString = "{\n" +
"\"expand\" : \"names\",\n" +
"\"customfield_1\" : null,\n" +
"\"customfield_2\" : [ { \"email\":\"123#gmail.com\"},{ \"email\":\"abc#gmail.com\"}]\n" +
"}";
JSONObject myObj = new JSONObject(jsonString);
JSONArray myArr1 = myObj.isNull("customfield_1") ? null : myObj.getJSONArray("customfield_1");
JSONArray myArr2 = myObj.isNull("customfield_2") ? null : myObj.getJSONArray("customfield_2");
System.out.println(myArr1);
System.out.println(myArr2);
Output:
null
[{"email":"123#gmail.com"},{"email":"abc#gmail.com"}]
Using object mapper, you can read json and setting deserialization feature FAIL_ON_UNKNOWN_PROPERTIES as false can handle this scenario
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyObject jsonObj = mapper.readValue(jsonString, MyObject.class);

Json object in Map, how to get hold of it in java?

In an XPages application I have in a sessionScope variable the configuration for the application in JSON format.
I wonder how I can get hold of this configuration again in Java?
I tried:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")){
JsonJavaObject jsonObject = new JsonJavaObject();
jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
In the console I never get to the "got object?" print statement. What am I doing wrong?
The JavaScript method JSON.parse that you use, returns just a plain simple JavaScript object, not the JsonJavaObject. You can't use JavaScript object later in Java without additional unnecessary overhead. Don't use json2.jss, use JsonParser like Paul Withers have told.
Change your code that gets JSON from your Notes field:
#{javascript:
importPackage(com.ibm.commons.util.io.json);
var jsonText = doc.getItemValueString(itemname);
var jsonFactory:JsonFactory = JsonJavaFactory.instanceEx;
var jsonObject = JsonParser.fromJson(jsonFactory, jsonText);
sessionScope.put('configJSON', jsonObject);
}
Modify your provided java code by removing unnecessary line:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")) {
JsonJavaObject jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
You should now be OK.
Hint: if you use JsonJavaFactory.instance instead of JsonJavaFactory.instanceEx, you'll get java.util.HashMap instead of JsonJavaObject
Has the sessionScope variable been set? Use sesScope.containsKey("configJSON") to verify. If it's an empty JSON object it will be "{}" rather than null. If you're loading as JSON from a REST service or a Notes Document it may be a String rather than a JsonJavaObject. For parsing a String of JSON, you can use com.ibm.commons.util.io.json.JsonParser. The constructor for JsonJavaObject expects a Map, not sure if this is what's being passed in.
JsonJavaObject is your POJO java class ?
If Yes then please use ObjectMapper of Fasterxml to map your JSON data to the fields of JsonJavaObject class.Use this method to map your json data to any POJO class
public final T validateJson(final Map<String, Object> jsonMap, final T temmplateClass) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
try {
// convert JSON string to Map
String jsonString = objectMapper.writeValueAsString(jsonMap);
return objectMapper.readValue(jsonString, (Class<T>) temmplateClass);
} catch (JsonMappingException e) {
throw new NestableRuntimeException(String.format(ApiCommonConstants.INVALID_JSON_FIELD,
e.getPath().get(e.getPath().size() - 1).getFieldName()));
} catch (IOException e) {
throw new NestableRuntimeException(e.getMessage(), e);
}
}

Parsing JSON in Java Play

I have a simple JSON object I wish to parse in Play, I am currently trying the following but having no luck:
HashMap<String,Object> result = new ObjectMapper().readValue(stringBuilder.toString(), HashMap.class);
My JSON Object looks like the following:
[{"id":"537b4f2e30047c51863094dd","from":"jacob","to":"duncan","subject":"Welcome to the message system!","message":"Hello World"},{"id":"537bb23930044f26cfd24464","from":"jacob","to":"duncan","subject":"Welcome to the message system!","message":"Hello World"}]
Can anybody provide an example on how to parse and iterate over this?
Play 2 uses Jackson API for JSON, so you should use it
Sample:
String jsonString = "[{\"id\":\"537b4f2e30047c51863094dd\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"},{\"id\":\"537bb23930044f26cfd24464\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"}]";
JsonNode node = Json.parse(jsonString);
if (node.isArray()) {
Iterator<JsonNode> elements = node.elements();
while (elements.hasNext()) {
JsonNode obj = elements.next();
debug(
"Message with ID: " + obj.get("id")
+ " from: " + obj.get("from")
+ " to: " + obj.get("to")
+ " subject: " + obj.get("subject")
+ " message: " + obj.get("message")
);
}
}
Tip: It was refactored some time ago, so depending on used Play version check Codehaus Jackson or FasterXML Jackson APIs
It looks like you've got a list, where each entry is a map key value pairs.
You can use a standard json parser to convert it into an object like this:
String json = "[{\"id\":\"537b4f2e30047c51863094dd\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"},{\"id\":\"537bb23930044f26cfd24464\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"}]";
Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
List<Map<String, Object>> data = new Gson().fromJson(json, listType);
Then you can iterate over the List and each Map as normal:
for (Map<String, Object> map : data) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
// do stuff
}
}
P.S.
It looks like all your value data is also in String form, so you might want to consider making a Map<String, String> instead of Map<String, Object> if that's actually the case.

String value as Object key

Let's say I've got String A = "A"; and String B = "B"; and I want to use these values as keys in a json object.
{
"A":"string1",
"B":"string2"
}
Now in another time and space, I'd like to get these String values from the Json Object. I'd have to get the value for "A" and "B". We can just use A and B when making this json object and reuse them when getting the values.
However, I'm trying to make a Json Object from an actual Object. I'm using Gson to achieve this. How can I use A and B as keys when making the object?
Using Gson you can parse the JSON into a Map as
String json = "{\n" +
"\"A\":\"string1\",\n" +
"\"B\":\"string2\"\n" +
"}";
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
System.out.println(map.get("A")); // string1
System.out.println(map.get("B")); // string2
Alternatively, if you want to wrap the keys in an already existing object
String json = "{ pairs : {\n" +
"\"A\":\"string1\",\n" +
"\"B\":\"string2\"\n" +
"} }";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
System.out.println(jsonObject.getPairs().get("A")); // string1
System.out.println(jsonObject.getPairs().get("B")); // string2
where the JsonObject could look like
class JsonObject {
private Map<String, String> pairs;
public Map<String, String> getPairs() {
return pairs;
}
}

Categories