Am getting response from ElasticSearch, from that response i want to form another JSON with limited fields (like custom JSONObject).
Please find the response that am getting from elastic search.
{
"took":93,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"skipped":0,
"failed":0
},
"hits":{
"total":1,
"max_score":1.0,
"hits":[
{
"_index":"attachment",
"_type":"doc",
"_id":"87740",
"_score":1.0,
"_source":{
"app_language":"ES",
"filetype":"PB",
"attachment":{
"date":"2006-05-03T15:17:53Z",
"content_type":"application/pdf",
"author":"JJamesN",
"language":"en",
"title":"Microsoft Word - te7000pb.doc",
"content":"European Electronic Controls Catalog ",
"content_length":12267
},
"ext":"pdf",
"fileContent":"JVBERi0xLjQNJeLjz9MNCjQ3ID"
}
}
]
}
}
Please find my java code that am trying to manipulate the response JSON to create a separate JSON with limited fields.
JSONObject jsonObject = new JSONObject(responseBody);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray hitsArray=hits.getJSONArray("hits");
System.out.println("Hits---->"+hitsArray.toString());
From the response JSON, i just want to create a new JSON with the following Structure and fields.
{
"app_language":"ES",
"filetype":"PB",
"attachment.content" : "European Electronic Controls Catalog ",
"ext":"pdf",
}
Try this:
JSONObject jsonBody = new JSONObject();
jsonBody.put("app_language","value");
jsonBody.put("filetype","value");
jsonBody.put("attachment.content","value");
jsonBody.put("ext",ext);
//String requestBody = jsonBody.toString();
Just extract your values from response and use it any where you want.
Hope this helps.
Related
I want all the URL present under the "endpoints" json.
I tried with access it through converting the String to JSON and after that using JSON parsar. But couldn't successed.
{
"process":{
"id":"epsswitch/process/create-switch-bdl",
"views":{
"selection":{
"uri":"//scp/sdf/sdf/s/df",
"controller":"scp/switching/createswitchingbdl/controllers/selection"
},
"customers":{
"uri":"//scp/vv/vv/views/Customers",
"controller":"scp/x/vc/controllers/customers"
},
"instructions":{
"uri":"//scp/df/fd/views/Information",
"controller":"scp/switching/fd/controllers/instructions"
},
"confirm":{
"uri":"//scp/switching/createswitchingbdl/views/Confirmation",
"controller":"scp/switching/createswitchingbdl/controllers/confirm"
}
},
"endpoints":{
"data":{
"uri":"/epsswitch/create/data?cc=true&al=true&ac=true"
},
"bank":{
"uri":"/fdd/df/df/v1/bank/df/",
"method":"GET"
}
}
}
There are multiple ways you can parse an JSON string. I use json simple (org.json.simple), java json are some of them. The following code uses the latter. It takes all the keys from the json string and retrieves all the values inside each key.
String sJSONString = "<your json object here>";
JSONObject jsObjects = new JSONObject(sJSONString);
//This is where you get your keys
Iterator<String> keys = jsObjects.keys();
//Use while if you need to poll for each key in JSON string
while(keys.hasNext())
{
String keyN = keys.next();
JSONObject jsoObjN = new JSONObject();
jsoObjN = (JSONObject)jsObjects.get(keyN);
//<Your logic here>
}
Following code help me to achive this.
final JsonNode studentNode = mapper.readTree(sPhone.getProcessJson());
JsonNode process = studentNode.get("process");
JsonNode endpoints = process.get("endpoints");
for (JsonNode jsonNode : endpoints) {
JsonNode uri = jsonNode.get("uri");
}
I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");
I'm trying to get the data of this Json. As you can see the first element have a json inside of the json.
{
"client":{
"colour":"aabb11",
"height":200,
"xpos":0,
"packages":"com.samsung.incallUi",
"events":[
{
"action":"hide",
"class":"com.android.TextView",
"type":"2"
},
{
"colour":"00FF00",
"action":"show"
}
],
"width":600,
"ypos":20
},
"Map":" {red=blue, yellow=brown}",
"Country":"IT"
}
I get the json from:
Request request = new Request.Builder().url(INIT_URL).post(formBody).build();
Response response = client.newCall(request).execute();
I'm trying this, but don't work (give me an JsonSyntaxException):
...
JSONArray ja = new JSONArray(response.body().string());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String client = jo.getString("client");
String xpos = jo.getString("height");
String packages = jo.getString("xpos");
String events = jo.getString("packages");
...
}
...
The first element, "client" is an object not an array.
try
JSONObject ja= new JSONObject(response.body().string());
I recommend you to take a look into a JSON parser, such us Jackson or Gson.
Will do your life much easier.
//Jackson example
Client client = new ObjectMapper().readValue(jsonString, Client.class);
Just define your Client class with the fields in the JSON
I strongly recommend using Gson. If you can't get it right with gson, that means, your model is not correct. If you have a hard time creating the model for the json, you can auto generate the model instead of creating it your self.
I am trying to extract a person's details who liked a facebook page by passing the page id as parameter. I extracted the JSON content of that page and now from that I want to extract name and id of users.
How do I achieve that ?
Code:
JSONObject json = readurl("https://graph.facebook.com/pageid");
System.out.println(json.toString());
System.out.println("Page id is:"+json.get("id"));
JSON:
"likes":{
"data":[
{
"id":"*******",
"name":"vv"
},
{
"id":"********",
"name":"abc"
},
Code like this would do the trick.
JSONObject json = readurl("https://graph.facebook.com/pageid");
JSONArray dataJsonArray = json.getJSONArray("data");
for(int i=0; i<dataJsonArray.length; i++) {
JSONObject dataObj = dataJsonArray.get(i);
String id = dataObj.getString("id");
//Similarly you can extract for other fields.
}
Basically data is a JSONArray since it starts with [. So simply get would not work, you must use JSONArray.
Note: I haven't compiled this code, but I think I gave you idea to proceed. Also refer this link to get hold of basics of parsing JSON in java.
This snippet is not tested, but I'm pretty sure it works:
JSONArray data = json.getJSONArray("data");
for (int i=0; i < data.length(); i++) {
JSONObject o = data.getJSONObject(i);
sysout(o.getString("id");
sysout(o.getString("name");
}
I use google's Gson library from: https://code.google.com/p/google-gson/
This is my String gathered from a JSON file. It is as expected:
{
"catalog":{
"book":{
"id":"bk101",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications with XML."
}
}
}
Using this String I created a JSONObject..
JSONObject jsonBook = new JSONObject(sb.toString());
Then I am simply trying to extract some of the parameters seen in the string such as id and author.
"id": "bk101"` `"author": "Gambardella, Matthew"
This is my approach..
book.setAuthor(jsonBook.getString(Book.AUTHOR));
book.setId(jsonBook.getString(Book.ID));
Yet I keep getting errors saying there is no value for id/author whichever one is first. Any ideas?
Cheers
That's because id and author are both inside book, not inside the json root
JSONObject jsonBook = new JSONObject(sb.toString());
JSONObject catalogue = jsonBook.getJSONObject("catalog");
JSONObject jbook = catalogue.getJSONObject("book");
book.setAuthor(jbook.getString(Book.AUTHOR));
book.setId(jbook.getString(Book.ID));