I would like to parse the following JSON response, using GSON. As you can see, there are a lot of inner json objects in the response. Do I need to create POJO classes for all the inner objects or is there any alternative?
{
"nodeProperties": [
{
"properties": {
"timeStamp": {
"value": 1400475483694,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:03"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"tier": {
"value": 1
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "NEXT_NEWSwitch3"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:03",
"type": "OF"
}
},
{
"properties": {
"timeStamp": {
"value": 1400475481261,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:02"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"tier": {
"value": 1
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "None"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:02",
"type": "OF"
}
},
{
"properties": {
"timeStamp": {
"value": 1400475478695,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:01"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "None"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
}
}
]
}
Simply convert the JSON string into Map.
Sample code:
FileReader in = new FileReader(new File("resources/json3.txt"));
BufferedReader br = new BufferedReader(in);
// Convert JSON string into MAP object
Gson gson = new Gson();
Type type = new TypeToken<Map<String, ArrayList<Map<String, Map<String, Object>>>>>() {}.getType();
Map<String, ArrayList<Map<String, Map<String, Object>>>> map = gson.fromJson(br, type);
for (String key : map.keySet()) {
System.out.println(key);
for (Map<String, Map<String, Object>> value : map.get(key)) {
for (String k : value.keySet()) {
System.out.println(k);
for (String k1 : value.get(k).keySet()) {
System.out.println(k1 + ":" + value.get(k).get(k1));
}
}
System.out.println("--------------");
}
}
in.close();
br.close();
You can do it using some POJO classes as well which are replica of the JSON string that is more simple and shorter.
Sample code:
class PropertiesNode {
Properties properties;
Node node;
// getter & setter
}
class Node {
String id;
String type;
// getter & setter
}
class Properties {
Map<String, Object> timeStamp;
Map<String, String> macAddress;
Map<String, Integer> tables;
Map<String, Integer> capabilities;
Map<String, Integer> tier;
Map<String, String> supportedFlowActions;
Map<String, Integer> buffers;
Map<String, String> description;
Map<String, Integer> forwarding;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<Map<String, ArrayList<PropertiesNode>>>() {}.getType();
Map<String, ArrayList<PropertiesNode>> nodeProperties = gson.fromJson(br, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(nodeProperties).toString());
output:
{
"nodeProperties": [
{
"properties": {
"timeStamp": {
"value": 1.400475483694E12,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:03"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"tier": {
"value": 1
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "NEXT_NEWSwitch3"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:03",
"type": "OF"
}
},
{
"properties": {
"timeStamp": {
"value": 1.400475481261E12,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:02"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"tier": {
"value": 1
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "None"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:02",
"type": "OF"
}
},
{
"properties": {
"timeStamp": {
"value": 1.400475478695E12,
"name": "connectedSince"
},
"macAddress": {
"value": "00:00:00:00:00:01"
},
"tables": {
"value": -1
},
"capabilities": {
"value": 199
},
"supportedFlowActions": {
"value": "[Controller, Drop, Enqueue, HwPath, Output, PopVlan, SetDlDst, SetDlSrc, SetNwDst, SetNwSrc, SetNwTos, SetTpDst, SetTpSrc, SetVlanId, SetVlanPcp, SwPath]"
},
"buffers": {
"value": 256
},
"description": {
"value": "None"
},
"forwarding": {
"value": 0
}
},
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
}
}
]
}
Related
I'm having an issue comparing two json because some times the json that I recive from DB is oldEncodedString has values unordered
private static boolean encodeProduct(BaseProduct baseProduct) {
boolean saveProduct = false;
try {
saveProduct = true;
String oldEncodedString = baseProduct.getEncodedJson();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
String json = objectMapper.writeValueAsString(baseProduct);
Objects.requireNonNull(baseProduct).setEncodedJson(json);
if (Objects.nonNull(oldEncodedString) && JSONCompare.compareJSON(oldEncodedString, baseProduct.getEncodedJson(), JSONCompareMode.STRICT).passed()) {
saveProduct = false;
}
} catch (Exception exception) {
LOG.error("Error generating encode", exception);
}
return saveProduct;
}
eg:
oldEncodedString = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1003", "type": "Blueberry" },
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1004", "type": "Devil's Food" }
]
}}
baseProduct.getEncodedJson =
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
}}
So the values are unordered and when I compare into that if with STRICT is said that is not the same , but because is not ordered the values I tryed adding ObjectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
but is not on this library
I am trying to see the following message on slack:
{
"blocks": [{
"type": "actions",
"elements": [{
"type": "button",
"text": {
"type": "plain_text",
"text": "Farmhouse",
"emoji": true
},
"value": "click_me_123"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Kin Khao",
"emoji": true
},
"value": "click_me_123",
"url": "https://google.com"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Ler Ros",
"emoji": true
},
"value": "click_me_123",
"url": "https://google.com"
}
]
}]
}
Now on the java side I am using gson to map this to an object and then send it using ctx.say():
List<LayoutBlock> blocks = answers.stream().map(ans ->
gson.fromJson(ans.getContent(), LayoutBlock.class)
).collect(Collectors.toList());
Now this mapping fails. If I try to use a simpler json it works:
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Option 1",
"emoji": true
},
"value": "{ \"name\": \"smalltalk.appraisal.thank_you\", \"entities\": { \"reply\": \"test\", \"option\": \"1\" } }"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Option 2",
"emoji": true
},
"value": "{ \"name\": \"smalltalk.appraisal.thank_you\", \"entities\": { \"reply\": \"test\", \"option\": \"2\" } }"
}
]
}
Basically what I'm seeing is that when using ctx.say(), you can either send a String or a List of Blocks:
default ChatPostMessageResponse say(String text) throws IOException, SlackApiException {
this.verifyChannelId();
ChatPostMessageResponse response = this.client().chatPostMessage(ChatPostMessageRequest.builder().text(text).channel(this.getChannelId()).build());
return response;
}
default ChatPostMessageResponse say(List<LayoutBlock> blocks) throws IOException, SlackApiException {
this.verifyChannelId();
ChatPostMessageResponse response = this.client().chatPostMessage(ChatPostMessageRequest.builder().blocks(blocks).channel(this.getChannelId()).build());
return response;
}
How am I supposed to convert the json shown in the slack block kit builder into a java object that can actually be sent using ctx.say()?
Here below the json format:
Document{
{Social=4, Productivity=5, Personalization=1, Entertainment=5, Music & Audio=4, Finance=7, Tools=9, Travel & Local=1, Food & Drink=3, Card=1, Photography=5, OTHERS=4, Shopping=4, Maps & Navigation=2, Communication=5, Business=3, Video Players & Editors=3
}}
Here I need only keys no need of values.
I am expecting this kind of output:
{
"name": "Social",
"value": "Social"
},
{
"name": "Productivity",
"value": "Productivity"
}
{
"name": "Personalization",
"value": "Personalization"
}
{
"name": "Entertainment",
"value": "Entertainment"
}
{
"name": "Music & Audio",
"value": "Music & Audio"
}
{
"name": "Finance",
"value": "Finance"
}
{
"name": "Tools",
"value": "Tools"
}
{
"name": "Travel & Local",
"value": "Travel & Local"
}
{
"name": "Food & Drink",
"value": "Food & Drink"
}
{
"name": "Card",
"value": "Card"
}
{
"name": "Photography",
"value": "Photography"
}
{
"name": "OTHERS",
"value": "OTHERS"
}
{
"name": "Shopping",
"value": "Shopping"
}
{
"name": " Maps & Navigation",
"value": " Maps & Navigation"
}
{
"name": "Communication",
"value": "Communication"
}
{
"name": "Business",
"value": "Business"
}
{
"name": "Productivity",
"value": "Productivity"
}
I am not getting a proper solution.
for (Document doc : documents) {
doc.entrySet().forEach(v -> {
SegmentValueOptions inputValues = new SegmentValueOptions();
inputValues.setName(v.getKey());
inputValues.setValue(inputValues.getName());
inputValList.add(inputValues);
});
}
}
I have a JSON response coming from Hubspot API as following, I am having trouble to parse it into Java POJO for using with RestTemplate.
Since the Json reponse is not in form of json arrays,I am not able to create proper java classes.
Can someone please help?
The JSON response received is as following:
{
"1": {
"vid": 1,
"canonical-vid": 1,
"portal-id": 5017510,
"is-contact": true,
"profile-token": "AO_T-mOzMc0AQx3P50QBw3qJ09A30BWfeQu89iOhW5ADWb6-uIT7m37lYwSTk7ObLEYwwnpxGNM1x9rkivaT-abeu6MegOWO31EUpZ3b56hfFti61ewcGQvC-XocjM2fekCOtK5oyM1C",
"profile-url": "https://app.hubspot.com/contacts/5017510/lists/public/contact/_AO_T-mOzMc0AQx3P50QBw3qJ09A30BWfeQu89iOhW5ADWb6-uIT7m37lYwSTk7ObLEYwwnpxGNM1x9rkivaT-abeu6MegOWO31EUpZ3b56hfFti61ewcGQvC-XocjM2fekCOtK5oyM1C/",
"properties": {
"firstname": {
"value": "Cool"
},
"city": {
"value": "Cambridge"
},
"createdate": {
"value": "1539332326199"
},
"company": {
"value": "HubSpot"
},
"state": {
"value": "MA"
},
"email": {
"value": "coolrobot#hubspot.com"
},
"website": {
"value": "http://www.HubSpot.com"
},
"jobtitle": {
"value": "Robot"
},
"lastmodifieddate": {
"value": "1539332330206"
},
"lastname": {
"value": "Robot (Sample Contact)"
}
}
},
"51": {
"vid": 51,
"canonical-vid": 51,
"portal-id": 5017510,
"is-contact": true,
"profile-token": "AO_T-mNsLUnhG0QdyfV6D_JZhoqldgC_jYOZswkSrsgRW1uvUZpajXSjd-83OtQEdptpio0VAgtGD3_qIOe_4vnijJ8_q6traOskjw5A48d1RhghdFuqiDpgz7pRcuzTrMjsvWF5Oat3",
"profile-url": "https://app.hubspot.com/contacts/5017510/lists/public/contact/_AO_T-mNsLUnhG0QdyfV6D_JZhoqldgC_jYOZswkSrsgRW1uvUZpajXSjd-83OtQEdptpio0VAgtGD3_qIOe_4vnijJ8_q6traOskjw5A48d1RhghdFuqiDpgz7pRcuzTrMjsvWF5Oat3/",
"properties": {
"firstname": {
"value": "Brian"
},
"city": {
"value": "Cambridge"
},
"createdate": {
"value": "1539332326434"
},
"company": {
"value": "HubSpot"
},
"state": {
"value": "MA"
},
"email": {
"value": "bh#hubspot.com"
},
"website": {
"value": "http://www.HubSpot.com"
},
"jobtitle": {
"value": "CEO"
},
"lastmodifieddate": {
"value": "1539332334158"
},
"lastname": {
"value": "Halligan (Sample Contact)"
}
}
}
}
See this link, http://www.jsonschema2pojo.org/ in it you pass the JSON and it mounts the POJO for you, however you want.
I tested with your JSON and generated perfectly.
you can use Jackson to convert JSON response into POJO class.
Sample code:
ObjectMapper mapper = new ObjectMapper();
POJOClass pojoclassObj = mapper.readValue(jsonResponse, POJOClass.class);
I'm trying to insert an object to a nested array through the java api, but I get the following error
MapperParsingException[object mapping for [X] tried to parse field [null] as object, but found a concrete value]
doing it through Kibana as shown below the same script works.
Any ideas on how to fix this?
The java code is the following
HashMap<String, Object> params = new HashMap<>();
params.put("object", objectAsString);
Script script = new Script(ScriptType.INLINE, "painless", "ctx._source.media.add(params.object)", params);
UpdateResponse result = elasticClient.prepareUpdate(indexName, "Type", documentId).setScript(script).execute().actionGet();
Trhough Kibana
POST index/document/id/_update
{
"script": {
"lang": "painless",
"inline": "ctx._source.media.add(params.object)",
"params": {
"object": {
"description" : "A second image",
"height" : 5,
"weight": 5,
"name" : "Test",
"orientation" : "Vertical",
"url" : "htttp://newurl.jpg",
"tags":["first","second"],
"type":"image"
}
}
}
}
The template mapping is the following:
"mappings": {
"FOLDER_MODULE": {
"properties": {
"name": {
"type": "keyword"
},
"publisherId": {
"type": "keyword"
},
"username": {
"type": "keyword"
},
"media": {
"type": "nested",
"properties": {
"id": {
"type": "text"
},
"name": {
"type": "text"
},
"publisherId": {
"type": "short"
},
"tags": {
"type": "text"
},
"description": {
"type": "text"
},
"url": {
"type": "keyword"
},
"createdDate": {
"format": "strict_date_optional_time||epoch_millis",
"type": "date"
},
"height": {
"type": "float"
},
"width": {
"type": "float"
},
"weight": {
"type": "float"
},
"orientation": {
"type": "keyword"
},
"status": {
"type": "keyword"
},
"type": {
"type": "keyword"
},
"username": {
"type": "keyword"
}
}
}
}
}
}