{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"likecount": 0,
"unlikeCount": 0,
"shareCount": 0,
"i_id": 297,
"p_id": 297,
"name": "Airport runways columbia hon",
"description": "Airport runways columbia hongkong aviation airplanes aeroplanes",
"c_id": 1,
"status_id": 1,
"source_id": 149,
"date_created": null,
"parentinfograph": "Staffing insurance liability ",
"internal_url": "http://167.99.86.81:8000/media/DQ297.jpg",
"external_url": "http://www.aertecsolutions.com/wp-content/uploads/2017/03/Infographic-Runway-ENG.jpg",
"mt_id": 1,
"mtcode": "Business"
}
]
}
First of all, create a POJO class from JSON string using :
http://www.jsonschema2pojo.org/
Then, create an instance of POJO class. Now, using GSON, you can set the values in the instance. Lastly, you can get the value using getter method
For eg.
Usermodel usermodel = new Gson().fromJson(<JSON string>, UserModel.class);
Usermodel is my POJO class here.
Please check below:
#Test
public void getlikecount() {
String JSON = "{\r\n" +
" \"count\": 1,\r\n" +
" \"next\": null,\r\n" +
" \"previous\": null,\r\n" +
" \"results\": [\r\n" +
" {\r\n" +
" \"likecount\": 0,\r\n" +
" \"unlikeCount\": 0,\r\n" +
" \"shareCount\": 0,\r\n" +
" \"i_id\": 297,\r\n" +
" \"p_id\": 297,\r\n" +
" \"name\": \"Airport runways columbia hon\",\r\n" +
" \"description\": \"Airport runways columbia hongkong aviation airplanes aeroplanes\",\r\n" +
" \"c_id\": 1,\r\n" +
" \"status_id\": 1,\r\n" +
" \"source_id\": 149,\r\n" +
" \"date_created\": null,\r\n" +
" \"parentinfograph\": \"Staffing insurance liability \",\r\n" +
" \"internal_url\": \"http://167.99.86.81:8000/media/DQ297.jpg\",\r\n" +
" \"external_url\": \"http://www.aertecsolutions.com/wp-content/uploads/2017/03/Infographic-Runway-ENG.jpg\",\r\n" +
" \"mt_id\": 1,\r\n" +
" \"mtcode\": \"Business\"\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
JsonPath jsonpath = new JsonPath(JSON);
System.out.println("value of key->likecount: "+jsonpath.getString("results.likecount[0]"));
}
Output: value of key->likecount: 0
Related
I have a JSON file as below and want to convert to json with Name key , value pair ,
Eg : "name":"emailAddress",
"value" :"Trest22#gmail.com"
If have multiple JSON tags then it should break into separate tag as shown in image.
Please help
[
{
"emailAddress": "Trest22#gmail.com",
"loginName": "Testinguser222",
"firstName": "Test222",
"surName": "Test22",
"primaryPhone": "",
"companyId": 123445,
"extracompanies": "[12311,33333]",
"middleName": "Test",
"mobilePhone": 6666666666,
"fax": 87687687686
}
]
Want to convert as below
{
{
"name":"emailAddress",
"value" :"Trest22#gmail.com"
}
{
"name":"loginName",
"value":"Testinguser222"
}
{
"name":"firstName",
"value":"Test222"
}
{
"name":"surName",
"value":"Test22"
}
{ "name":"extracompanies",
"value": "[12311,33333]"
}
I am not sure if any library can do that, however, in Java, you can achieve it as shown below,
ObjectMapper mapper = new ObjectMapper();
String test = "{\n" +
" \"emailAddress\": \"Trest22#gmail.com\",\n" +
" \"loginName\": \"Testinguser222\",\n" +
" \"firstName\": \"Test222\",\n" +
" \"surName\": \"Test22\",\n" +
" \"primaryPhone\": \"\",\n" +
" \"companyId\": 123445,\n" +
" \"extracompanies\": \"[12311,33333]\",\n" +
" \"middleName\": \"Test\",\n" +
" \"mobilePhone\": 6666666666,\n" +
" \"fax\": 87687687686\n" +
" \n" +
" }";
Map<String, Object> maps = mapper.readValue(test, Map.class);
List<Map<String,Object>> converted = maps.keySet().stream().map(key -> {
Map<String,Object> internalMap = new HashMap<>();
internalMap.put("name", key);
internalMap.put("value", maps.get(key));
return internalMap;
}).collect(Collectors.toList());
String json = mapper.writeValueAsString(converted);
Output
[{"name":"emailAddress","value":"Trest22#gmail.com"},{"name":"loginName","value":"Testinguser222"},{"name":"firstName","value":"Test222"},{"name":"surName","value":"Test22"},{"name":"primaryPhone","value":""},{"name":"companyId","value":123445},{"name":"extracompanies","value":"[12311,33333]"},{"name":"middleName","value":"Test"},{"name":"mobilePhone","value":6666666666},{"name":"fax","value":87687687686}]
I want to persist some historical data from my server. So the documentation says that you must first send a subscription to Orion and then Orion will send the notification to Cygnus.
I made the subscription like this:
Entity payload = Entity.json("{\r\n" +
" \"entities\": [{\r\n" +
" \"type\": \"Usuario\",\r\n" +
" \"isPattern\": \"true\",\r\n" +
" \"id\": \"Usuario*\"\r\n" +
" }],\r\n" +
" \"attributes\": [],\r\n" +
" \"reference\": \"http://192.168.10.3:5050/notify\",\r\n" +
" \"duration\": \"P4Y\",\r\n" +
" \"notifyConditions\": [{\r\n" +
" \"type\": \"ONCHANGE\",\r\n" +
" \"condValues\": [\r\n" +
" \"speed\"\r\n" +
" ]\r\n" +
" }],\r\n" +
" \"throttling\": \"PT0.001S\"\r\n" +
"}");
Response response = client.target("http://192.168.10.3:1026/v1/subscribeContext")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(payload);
And the creation of entities:
Entity payload = Entity.json("{ \"type\": \"Usuario\", \"id\": \"Usuario22\", \"temperature\": { \"value\": \"80.0\" }, \"location\": { \"value\": \""+latitud+", "+altitud+"\", \"type\": \"geo:point\", \"metadata\": { \"crs\": { \"value\": \"WGS84\" } } }}");
Response response = client.target("http://192.168.10.3:1026/v2/entities")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(payload);
Then, Cygnus log tell me:
HTTPBadRequestException: 'fiware-servicepath' header value does not match the number of notified context responses [...]
Do any of you know why this is happening? The creation of the headers should be done by Orion or, failing that, by using the configuration of the Cygnus...
Thank you in advance.
UPDATE:
I have changed the http client of the server to make it easier to incorporate headers.
My subscription:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://192.168.10.3:1026/v1/subscribeContext");
String json = "{\r\n" +
" \"entities\": [{\r\n" +
" \"type\": \"cargador\",\r\n" +
" \"isPattern\": \"true\",\r\n" +
" \"id\": \"cargador*\"\r\n" +
" }],\r\n" +
" \"attributes\": [\"speed\"],\r\n" +
" \"reference\": \"http://192.168.10.3:5050/notify\",\r\n" +
" \"duration\": \"P4Y\",\r\n" +
" \"notifyConditions\": [{\r\n" +
" \"type\": \"ONCHANGE\",\r\n" +
" \"condValues\": [\r\n" +
" \"speed\"\r\n" +
" ]\r\n" +
" }],\r\n" +
" \"throttling\": \"PT0.001S\"\r\n" +
"}";
StringEntity entity;
try {
entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("fiware-servicepath", "/");
CloseableHttpResponse response;
response = client.execute(httpPost);
System.out.println(response.getStatusLine());
client.close();
} catch (UnsupportedEncodingException e1) {
My update context:
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).build();
HttpPost httpPost = new HttpPost("http://192.168.10.3:1026/v1/updateContext");
String json = "{\r\n" +
" \"contextElements\": \r\n" +
"\r\n" +
" \r\n" +
"\r\n" +
" [\r\n" +
" {\r\n" +
" \"type\": \"cargador\",\r\n" +
" \"isPattern\": \"false\",\r\n" +
" \"id\": \"cargador48\",\r\n" +
" \"attributes\": [\r\n" +
" {\r\n" +
" \"name\": \"speed\",\r\n" +
" \"type\": \"float\",\r\n" +
" \"value\": \"798\"\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ],\r\n" +
" \"updateAction\": \"APPEND\"\r\n" +
" }";
StringEntity entity;
try {
entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("fiware-servicepath", "/");
CloseableHttpResponse response;
response = client.execute(httpPost);
System.out.println(response.getStatusLine());
client.close();
And the trace I generate is like this:
Thank you again.
The error message you are receiving would seem to indicate that you are attempting to send a subscription to Cygnus using the newer NGSI v2 format however the current Cygnus release only accepts notifications in the older NGSI v1 format- the attrsFormat=legacy attribute is therefore required when setting up the subscription
See this question for more details about how to fix it.
I am using java to extract a list of node ids from an elastic search running tasks response.
The response looks like this
{
"nodes": {
"ZKUuxQZpRCCcJ0njBM1P0A": {
"name": "ZKUuxQZ",
"transport_address": "127.0.0.1:9300",
"host": "127.0.0.1",
"ip": "127.0.0.1:9300",
"roles": [
"master",
"data",
"ingest"
],
"tasks": {
"ZKUuxQZpRCCcJ0njBM1P0A:118": {
"node": "ZKUuxQZpRCCcJ0njBM1P0A",
"id": 118,
"type": "transport",
"action": "indices:data/write/delete/byquery",
"start_time_in_millis": 1527808643421,
"running_time_in_nanos": 154234724059,
"cancellable": true,
"headers": {}
}
}
}
}
}
In this example, I want to exact ZKUuxQZpRCCcJ0njBM1P0A:118. Can someone give me an example how to extract this information?
Option 1, java json parser. I wanted to write a response class and parse the json string, but ZKUuxQZpRCCcJ0njBM1P0A:118 is not in the key:value format. I am not sure how to extract it.
Option 2, using regex. The node id part may also have - or _. Can someone provide a neat java regex solution? So far my regex is [a-zA-Z0-9\-\_]+\:[0-9]+, I am not sure if this is safe enough.
Thanks.
One way you can do this is by using org.json library and create JSONObject and using keys() you can get all the keys and use this to achieve your task
Add the following dependency in your pom.xml
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
Then you can do something like below:
String jsonString = "{\n" +
" \"nodes\": {\n" +
" \"ZKUuxQZpRCCcJ0njBM1P0A\": {\n" +
" \"name\": \"ZKUuxQZ\",\n" +
" \"transport_address\": \"127.0.0.1:9300\",\n" +
" \"host\": \"127.0.0.1\",\n" +
" \"ip\": \"127.0.0.1:9300\",\n" +
" \"roles\": [\n" +
" \"master\",\n" +
" \"data\",\n" +
" \"ingest\"\n" +
" ],\n" +
" \"tasks\": {\n" +
" \"ZKUuxQZpRCCcJ0njBM1P0A:118\": {\n" +
" \"node\": \"ZKUuxQZpRCCcJ0njBM1P0A\",\n" +
" \"id\": 118,\n" +
" \"type\": \"transport\",\n" +
" \"action\": \"indices:data/write/delete/byquery\",\n" +
" \"start_time_in_millis\": 1527808643421,\n" +
" \"running_time_in_nanos\": 154234724059,\n" +
" \"cancellable\": true,\n" +
" \"headers\": {}\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
Set<String> topLevelKeys = jsonObject.keySet();
for (String key : topLevelKeys) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
JSONObject valueObject = jsonObject.getJSONObject(key);
System.out.println(valueObject.toString());
}
}
Extend this as per your requirement.
So regex is too hacky and I figured it out using gson. I wish ElasticSearch can offer us some standard library to extract all kinds of responses. Here is my solution using gson.
import com.google.gson.*;
import org.json.JSONObject;
public class test {
public static void main(String[] args) throws Exception {
String jsonString = "json_format elasticsearch reponse for listing running tasks"
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(content).getAsJsonObject();
jsonObject.getAsJsonObject("nodes").entrySet().forEach(
s -> {
s.getValue().getAsJsonObject().getAsJsonObject("tasks").entrySet().forEach( s2 -> {
System.out.println(s2.getKey());
});
});
}
It prints all the running task ids like the following. It's technically nodeId:taskId, but ES has a very vague description in their task API docs(It says you can use TASK_ID to check a status of a task, well that TASK_ID is nodeId:taskId).
Mw-3i39gTHGxu5c8z9viQQ:503209021
DZ29LMsWR0aW9guWZTYe2Q:482931604
6CAbDZSWR8SfwZgnRT0qNg:494351185
Use the following regex:
[a-zA-Z0-9-_]*[0-9]+[a-zA-Z]+:[0-9]*
You can find the test result here:
https://regexr.com/3qdug
Hi I'm trying to parse out the id's from an array. I have a logging method which shows a toast:
StringBuilder data= new StringBuilder();
JSONArray arrayMovies= response.getJSONArray(KEY_MOVIES);
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovie = arrayMovies.getJSONObject(i);
String id = currentMovie.getString(KEY_ID);
data.append(id+"\n");
}
L.t(getActivity(), data.toString());
.....
But It's not parsing it out. Just getting a list of the movies.
Here is the json file:
{
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"genre_ids": [
53,
28,
12
],
"id": 76341,
"original_language": "en",
"original_title": "Mad Max: Fury Road",
"overview": "An apocalyptic story set in the furthest reaches of our planet, in a stark desert landscape where humanity is broken, and most everyone is crazed fighting for the necessities of life. Within this world exist two rebels on the run who just might be"
}
]
}
Not sure, but maybe because id value has no quote, and therefore, can not be parsed as a String with getString() method
I think your code is OK, just need check the response and keys again, I have tested with hard-code the response as the String and 2 keys as the following:
String jsonString = "{\n" +
" \"page\": 1,\n" +
" \"results\": [\n" +
" {\n" +
" \"adult\": false,\n" +
" \"backdrop_path\": \"/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg\",\n" +
" \"genre_ids\": [\n" +
" 53,\n" +
" 28,\n" +
" 12\n" +
" ],\n" +
" \"id\": 76341,\n" +
" \"original_language\": \"en\",\n" +
" \"original_title\": \"Mad Max: Fury Road\",\n" +
" \"overview\": \"An apocalyptic story set in the furthest reaches of our planet, in a stark desert landscape where humanity is broken, and most everyone is crazed fighting for the necessities of life. Within this world exist two rebels on the run who just might be\"\n" +
" }\n" +
" ]\n" +
"}";
StringBuilder data= new StringBuilder();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray arrayMovies= jsonObject.getJSONArray("results");
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovie = arrayMovies.getJSONObject(i);
String id = currentMovie.getString("id");
data.append(id+"\n");
}
Log.i("BNK", data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And here is the screenshot (please pay attention to logcat):
Consider the following json example
{
"key1" : {
"k11":["vala","valb","valc"],
"k12":["vald"],
"k13":["vale","valf"]
},
"key2" : {
"key21":["valg","valh","vali"],
"key22":["valj"],
"key23":["valk","vall"]
}
}
This translates into a Map<String,Map<String,List<String>>>.
Could anyone please let me know how i can convert this in this into this complex Map object. I do a a method called constructMapType, but not sure if it handles complex Map type.
Seems to work fine with .constructMapType(Map.class, String.class, Map.class)
public static void main(String[] args) throws Exception {
final String json
= "{\n"
+ " \"key1\" : {\n"
+ " \"k11\":[\"vala\",\"valb\",\"valc\"],\n"
+ " \"k12\":[\"vald\"],\n"
+ " \"k13\":[\"vale\",\"valf\"]\n"
+ " },\n"
+ " \"key2\" : {\n"
+ " \"key21\":[\"valg\",\"valh\",\"vali\"],\n"
+ " \"key22\":[\"valj\"],\n"
+ " \"key23\":[\"valk\",\"vall\"]\n"
+ " }\n"
+ "}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, List<String>>> map
= mapper.readValue(json,TypeFactory.defaultInstance()
.constructMapType(Map.class, String.class, Map.class));
for (String outerKey: map.keySet()) {
System.out.println(outerKey + ": " + map.get(outerKey));
for (String innerKey: map.get(outerKey).keySet()) {
System.out.print(innerKey + ": [");
for (String listValue: map.get(outerKey).get(innerKey)) {
System.out.print(listValue + ",");
}
System.out.println("]");
}
}
}
You could go all the way down listing all the generics down to the List<String>, but as seen above it isn't necessary. But just to show what I mean
TypeFactory factory = TypeFactory.defaultInstance();
Map<String, Map<String, List<String>>> map
= mapper.readValue(json, factory.constructMapType(
Map.class,
factory.constructType(String.class),
factory.constructMapType(
Map.class,
factory.constructType(String.class),
factory.constructCollectionType(
List.class,
String.class))));