I have this json file I downloaded online:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
and I want to delete everything from
"empty": [
to
],
I've spent a few hours looking at regex stuff and I can't seem to figure out how to make it do what I want it to do.
Edit:
Annamalai Thangaraj's method works until I add more to the file.
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
which now I'm given an error:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject
My code is exactly:
public static void go() throws IOException {
JsonObject jsonObject = (JsonObject)JsonParser.parse(new FileReader(location));
jsonObject.remove("empty");
JsonArray jsonArray = (JsonArray)JsonParser.parse(new FileReader(location));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonObject.toString());
String prettyJsonString = gson.toJson(je);
FileWriter file = new FileWriter(System.getProperties().getProperty("user.home")+"\\output.json");
try {
file.write(prettyJsonString);
System.out.println("Successfully wrote JSON object to file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
}
Use the following code to remove element empty from json
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");
After removing empty element using jsonObject.toJSONString() to get target JSON, Now structure of JSON will be look like this
{
"price": 1,
"lowValue": 0,
"highValue": 0
},
Use a JSON library like Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public class JsonDelete {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"key\":\"value\",\"empty\":[]}";
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.remove("empty");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
}
}
Outputs:
{
"key" : "value"
}
If you put a '[' at the beginning and a ']' at the end of json file, it becomes a valid json file. Like in your json file, It should be.
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
]
So the final program will be like:--
public class ReadJSONFromFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("locationOfFIle"));
JSONArray array = (JSONArray) obj;
FileWriter file = new FileWriter("locationOfFIle");
for (int index = 0; index < array.size(); ++index) {
JSONObject jsonObject = (JSONObject) array.get(index);
jsonObject.remove("empty");
file.write(jsonObject.toJSONString());
file.flush();
if (index == array.size() - 1)
file.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can also parse your json by ignoring some fields. Look at this example:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#JsonIgnoreProperties(value = { "empty" })
public class Item {
private long price;
private long lowValue;
private long highValue;
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public long getLowValue() {
return lowValue;
}
public void setLowValue(long lowValue) {
this.lowValue = lowValue;
}
public long getHighValue() {
return highValue;
}
public void setHighValue(long highValue) {
this.highValue = highValue;
}
#Override
public String toString() {
return "Item [price=" + price + ", lowValue=" + lowValue + ", highValue=" + highValue + "]";
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String file = "c:\\json";
ObjectMapper mapper = new ObjectMapper();
Item[] items = mapper.readValue(new File(file), Item[].class);
for (Item item : items) {
System.out.println(item);
}
}
}
c:\json contains:
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 2,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 3,
"highValue": 4
}
]
Output is:
Item [price=1, lowValue=0, highValue=0]
Item [price=2, lowValue=3, highValue=4]
Related
I have stayed with the problem for more than 3 days of research but cant find any solvable solution. My android project makes a request to my gcloud functions and the function returns a string response with a String format:
[{"response": [{"Commission": 50, "Price": 0.5, "Quantity": "20"}, {"Commission": 50, "Quantity": 20, "Price": 1}, {"Quantity": 20, "Price": 10, "Commission": 50}], "code": 200}]
I was able to convert the string to JSON and retrieve the value of the "response" key.
try {
//convertion of response to json to fetch value
JSONObject jsonObj = new JSONObject("[{"response": [{"Commission": 50, "Price": 0.5, "Quantity": "20"}, {"Commission": 50, "Quantity": 20, "Price": 1}, {"Quantity": 20, "Price": 10, "Commission": 50}], "code": 200}]");
String code = jsonObj.getString("code");
final String Cod = code;
if (Cod.equals("200")){
String availableInv = jsonObj.getString("response");
availableInv = availableInv.replace("[", "");
availableInv = availableInv.replace("]", "");
String strng[] = availableInv.split("},");
for (String val:strng) {
int valLength = val.length();
if(!val.substring(valLength-1, valLength).contentEquals("}")) {
val +="}";
}
System.out.println(">>>>>>=====================response==========="+val);
JSONObject jsonObjInv = new JSONObject(val);
float price = Float.valueOf(jsonObjInv.getString("Price"));
float comission = Float.valueOf(jsonObjInv.getString("Commission"));
float quantity = Float.valueOf(jsonObjInv.getString("Quantity"));
myDataset.add(new InvestmentsModel(price,comission, quantity));
}
}
}
Now i want to be able to iterate through the list of the JSON object and fetch the keys and values.
When i run my solution i get the following error:
2020-03-24 16:17:55.235 4959-5006/com.example.SMS E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.SMS, PID: 4959
java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1
},
^
at java.util.regex.Pattern.compileImpl(Native Method)
at java.util.regex.Pattern.compile(Pattern.java:1340)
at java.util.regex.Pattern.<init>(Pattern.java:1324)
at java.util.regex.Pattern.compile(Pattern.java:946)
at java.lang.String.split(String.java:2384)
at java.lang.String.split(String.java:2426)
at com.example.SMS.Fragment.investEarnFrag_1$5.onResponse(investEarnFrag_1.java:251)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Seems that you find your answer in the comments. However, I think there is some point which is worth to emphasize here.
First of all, since you already decided to serialize your raw json response to a java object, which is JSONObject in this case, there is no point to parse the rest of the string anymore. You should stick with one of the methodologies to keep it consistent. So, in this case the methodology should be either parsing the whole json string or using org.json features. In my personal opinion, you should keep using the org.json.
Using org.json
The response you shared is in form of array/list of object.
[{"response": [{"Commission": 50, "Price": 0.5, "Quantity": "20"}, {"Commission": 50, "Quantity": 20, "Price": 1}, {"Quantity": 20, "Price": 10, "Commission": 50}], "code": 200}]
Since we have array of objects, we should use JSONArray to keep our json in.
JSONArray jsonArray = new JSONArray("[{\"response\": [{\"Commission\": 50, \"Price\": 0.5, \"Quantity\": \"20\"}, {\"Commission\": 50, \"Quantity\": 20, \"Price\": 1}, {\"Quantity\": 20, \"Price\": 10, \"Commission\": 50}], \"code\": 200}]");
// just to exemplify we get the first element, this should be depending on the business logic
JSONObject jsonObj = (JSONObject) jsonArray.get(0);
Now, we have the inner object in our jsonObj variable, which is:
{
"response": [
{
"Commission": 50,
"Price": 0.5,
"Quantity": "20"
},
{
"Commission": 50,
"Quantity": 20,
"Price": 1
},
{
"Quantity": 20,
"Price": 10,
"Commission": 50
}
],
"code": 200
}
So, we can easily get on key response which will be againg an array of object. We can easily iterate on it.
Note that in json all keys are string while values can be string, numeric, booelan and object. For instance, status can be parsed as integer.
try {
//convertion of response to json to fetch value
JSONArray jsonArray = new JSONArray("[{\"response\": [{\"Commission\": 50, \"Price\": 0.5, \"Quantity\": \"20\"}, {\"Commission\": 50, \"Quantity\": 20, \"Price\": 1}, {\"Quantity\": 20, \"Price\": 10, \"Commission\": 50}], \"code\": 200}]");
JSONObject jsonObj = (JSONObject) jsonArray.get(0);
int code = jsonObj.getInt("code");
List<InvestmentsModel> myDataset = new ArrayList<>();
if (code == 200){
JSONArray availableInv = jsonObj.getJSONArray("response");
for (Object val: availableInv) {
JSONObject value = (JSONObject) val;
float price = value.getFloat("Price");
float comission = value.getFloat("Commission");
float quantity = value.getFloat("Quantity");
myDataset.add(new InvestmentsModel(price,comission, quantity));
}
}
} catch (Exception e ) {
// todo handle exception
}
This can be a more naive answer to your question than parsing the raw response.
Taking one step further
It seems that we already have model class for InvestmentsModel. The more elegant approach is to keep things in their own contexts and to create for pojos for responses.
Assumed we have such InvestmentsModel:
import com.fasterxml.jackson.annotation.JsonProperty;
public class InvestmentsModel {
#JsonProperty("Price")
private float price;
#JsonProperty("Commission")
private float comission;
#JsonProperty("Quantity")
private float quantity;
public InvestmentsModel() {
}
public InvestmentsModel(float price, float comission, float quantity) {
this.price = price;
this.comission = comission;
this.quantity = quantity;
}
public InvestmentsModel price(float price) {
this.price = price;
return this;
}
public InvestmentsModel comission(float comission) {
this.comission = comission;
return this;
}
public InvestmentsModel quantity(float quantity) {
this.quantity = quantity;
return this;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getComission() {
return comission;
}
public void setComission(float comission) {
this.comission = comission;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return "[price -> " + this.price + ", comission -> " + this.comission + ", quantity -> " + this.quantity + "]";
}
}
For the response structure, we have:
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class GetInvestmentsResponseModel {
#JsonProperty("response")
private List<InvestmentsModel> response;
#JsonProperty("code")
private int code;
public GetInvestmentsResponseModel() {
}
public GetInvestmentsResponseModel(List<InvestmentsModel> response, int code) {
this.response = response;
this.code = code;
}
public GetInvestmentsResponseModel response(List<InvestmentsModel> response) {
this.response = response;
return this;
}
public GetInvestmentsResponseModel code(int code) {
this.code = code;
return this;
}
public List<InvestmentsModel> getResponse() {
return response;
}
public void setResponse(List<InvestmentsModel> response) {
this.response = response;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
And then code becomes:
final String rawResponse = "[{\"response\": [{\"Commission\": 50, \"Price\": 0.5, \"Quantity\": \"20\"}, {\"Commission\": 50, \"Quantity\": 20, \"Price\": 1}, {\"Quantity\": 20, \"Price\": 10, \"Commission\": 50}], \"code\": 200}]";
ObjectMapper mapper = new ObjectMapper();
try {
GetInvestmentsResponseModel[] responseObjects = mapper.readValue(rawResponse, GetInvestmentsResponseModel[].class);
GetInvestmentsResponseModel responseObject = responseObjects[0];
if(responseObject.getCode() == 200) {
List<InvestmentsModel> investmentsModels = responseObject.getResponse();
System.out.println(investmentsModels);
}
} catch (JsonProcessingException e) {
// handle JsonProcessingException
}
Outputs as just as in the InvestmentsModel's toString():
[[price -> 0.5, comission -> 50.0, quantity -> 20.0], [price -> 1.0, comission -> 50.0, quantity -> 20.0], [price -> 10.0, comission -> 50.0, quantity -> 20.0]]
Take one more step further
The final suggestion is to use swagger to both keep track of the api and get rid of the most of the boilerplate code. It can be used both clients and servers, and keeps APIs documented and clean. Please check this out for swagger.
I have the following JSON
"music": [
{
"play_offset_ms":10780,
"artists":[
{
"name":"Adele"
}
],
"lyrics":{
"copyrights":[
"Sony/ATV Music Publishing LLC",
"Universal Music Publishing Group"
]
},
"acrid":"6049f11da7095e8bb8266871d4a70873",
"album":{
"name":"Hello"
},
"label":"XL Recordings",
"external_ids":{
"isrc":"GBBKS1500214",
"upc":"886445581959"
},
"result_from":3,
"contributors":{
"composers":[
"Adele Adkins",
"Greg Kurstin"
],
"lyricists":[
"ADELE ADKINS",
"GREGORY KURSTIN"
]
},
"title":"Hello",
"duration_ms":295000,
"score":100,
"external_metadata":{
"deezer":{
"track":{
"id":"110265034"
},
"artists":[
{
"id":"75798"
}
],
"album":{
"id":"11483764"
}
},
"spotify":{
"track":{
"id":"4aebBr4JAihzJQR0CiIZJv"
},
"artists":[
{
"id":"4dpARuHxo51G3z768sgnrY"
}
],
"album":{
"id":"7uwTHXmFa1Ebi5flqBosig"
}
},
"musicstory":{
"track":{
"id":"13106540"
},
"release":{
"id":"2105405"
},
"album":{
"id":"931271"
}
},
"youtube":{
"vid":"YQHsXMglC9A"
}
},
"release_date":"2015-10-23"
}
]
I want to fetch the value vid from the youtube object in external_metadata. I am getting other required values but couldn't get the youtube id with what I tried. Just attaching a code snippet of what I tried.
I tried the following code:
try {
JSONObject j = new JSONObject(result);
JSONObject j1 = j.getJSONObject("status");
int j2 = j1.getInt("code");
if(j2 == 0){
JSONObject metadata = j.getJSONObject("metadata");
//
if (metadata.has("music")) {
wave.setVisibility(View.GONE);
JSONArray musics = metadata.getJSONArray("music");
for(int i=0; i<musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");}}
I did not get the expected output with what i tried , i know i am doing something wrong. Need your guidance.
I tried to run your code with sample JSON you have provided and It seems to work perfectly fine. I used google's gson library.
Below is the complete code.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String jsonString = "{ \"music\": [{ \"play_offset_ms\": 10780, \"artists\": [{ \"name\": \"Adele\" }], \"lyrics\": { \"copyrights\": [ \"Sony/ATV Music Publishing LLC\", \"Universal Music Publishing Group\" ] }, \"acrid\": \"6049f11da7095e8bb8266871d4a70873\", \"album\": { \"name\": \"Hello\" }, \"label\": \"XL Recordings\", \"external_ids\": { \"isrc\": \"GBBKS1500214\", \"upc\": \"886445581959\" }, \"result_from\": 3, \"contributors\": { \"composers\": [ \"Adele Adkins\", \"Greg Kurstin\" ], \"lyricists\": [ \"ADELE ADKINS\", \"GREGORY KURSTIN\" ] }, \"title\": \"Hello\", \"duration_ms\": 295000, \"score\": 100, \"external_metadata\": { \"deezer\": { \"track\": { \"id\": \"110265034\" }, \"artists\": [{ \"id\": \"75798\" }], \"album\": { \"id\": \"11483764\" } }, \"spotify\": { \"track\": { \"id\": \"4aebBr4JAihzJQR0CiIZJv\" }, \"artists\": [{ \"id\": \"4dpARuHxo51G3z768sgnrY\" }], \"album\": { \"id\": \"7uwTHXmFa1Ebi5flqBosig\" } }, \"musicstory\": { \"track\": { \"id\": \"13106540\" }, \"release\": { \"id\": \"2105405\" }, \"album\": { \"id\": \"931271\" } }, \"youtube\": { \"vid\": \"YQHsXMglC9A\" } }, \"release_date\": \"2015-10-23\" }] }";
public static void main(String[] args) throws Exception {
System.out.println("START");
readJson(jsonString);
System.out.println("END");
}
public static void readJson(String jsonString) throws Exception {
JsonObject metadata = new JsonParser().parse(jsonString).getAsJsonObject();
JsonArray musics = metadata.get("music").getAsJsonArray();
for (int i = 0; i < musics.size(); i++) {
JsonObject tt = musics.get(i).getAsJsonObject();
String title = tt.get("title").getAsString();
JsonArray artistt = tt.get("artists").getAsJsonArray();
JsonObject art = artistt.get(0).getAsJsonObject();
String artist = art.get("name").getAsString();
JsonObject extMETA = tt.get("external_metadata").getAsJsonObject();
JsonObject youtube = extMETA.get("youtube").getAsJsonObject();
String ytID = youtube.get("vid").getAsString();
System.out.println("ytID => "+ ytID);
}
}
}
Output:
Verify that the metadata variable has its value.
JSONObject jsonObject = new JSONObject(json);
Log.e("json structure : ", jsonObject.toString());
Use the following code when importing Json File from "Assets".
InputStream inputStream = getAssets().open("item.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json = new String(buffer, StandardCharsets.UTF_8);
If you have a Gson library, you can also access it in the "Class" format.
Gson gson = new Gson();
ItemVO itemVO = gson.fromJson(json, new TypeToken<ItemVO>() {
}.getType());
if (!itemVO.name != null) {
Log.e("name : ", itemVO.name);
} else {
Log.e("name : ", "name is Null");
}
Actual problem is in your JSONObject creation from sample data. Check below:
String data = "{\"metadata\":{\"timestamp_utc\":\"2020-01-02 09:40:56\",\"music\":[{\"play_offset_ms\":10780,\"artists\":[{\"name\":\"Adele\"}],\"lyrics\":{\"copyrights\":[\"Sony/ATV Music Publishing LLC\",\"Universal Music Publishing Group\"]},\"acrid\":\"6049f11da7095e8bb8266871d4a70873\",\"album\":{\"name\":\"Hello\"},\"label\":\"XL Recordings\",\"external_ids\":{\"isrc\":\"GBBKS1500214\",\"upc\":\"886445581959\"},\"result_from\":3,\"contributors\":{\"composers\":[\"Adele Adkins\",\"Greg Kurstin\"],\"lyricists\":[\"ADELE ADKINS\",\"GREGORY KURSTIN\"]},\"title\":\"Hello\",\"duration_ms\":295000,\"score\":100,\"external_metadata\":{\"deezer\":{\"track\":{\"id\":\"110265034\"},\"artists\":[{\"id\":\"75798\"}],\"album\":{\"id\":\"11483764\"}},\"spotify\":{\"track\":{\"id\":\"4aebBr4JAihzJQR0CiIZJv\"},\"artists\":[{\"id\":\"4dpARuHxo51G3z768sgnrY\"}],\"album\":{\"id\":\"7uwTHXmFa1Ebi5flqBosig\"}},\"musicstory\":{\"track\":{\"id\":\"13106540\"},\"release\":{\"id\":\"2105405\"},\"album\":{\"id\":\"931271\"}},\"youtube\":{\"vid\":\"YQHsXMglC9A\"}},\"release_date\":\"2015-10-23\"}]},\"cost_time\":0.2110002040863,\"status\":{\"msg\":\"Success\",\"version\":\"1.0\",\"code\":0},\"result_type\":0}";
try {
JSONObject jsonObject = new JSONObject(data);
JSONObject metadata = jsonObject.getJSONObject("metadata");
JSONArray musics = metadata.getJSONArray("music");
for (int i = 0; i < musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");
Log.v("VID", ytID);
}
} catch (Exception ex) {
ex.printStackTrace();
}
Elasticsearch Java client SearchResponse is unable to parse aggregation results. I've come across articles online which suggest adding aggregation types prefixed to the keys. I've added what I thought applies in my use case, such as "sterms# and sum#" but I am unable to figure out which type applies to the main filter (key:'matched' in my case). I am expecting the buckets object to be populated but it is currently being returned as an empty array despite response from elasticsearch containing aggregations.
Note: This is to be able to unit test.
Json response:
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 75,
"successful": 75,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 776329,
"max_score": 0,
"hits": []
},
"aggregations": {
"sterms#matched": {
"doc_count": 15,
"sterms#id": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "mykey",
"doc_count": 15,
"sterms#manufacturerName": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "subkey",
"doc_count": 15
}
]
},
"sum#totalCars": {
"value": 214244
},
"sum#totalTrucks": {
"value": 155738
}
}
]
}
}
}
}
Parser in Java
public static SearchResponse getSearchResponseFromJson(final String jsonFileName) {
try {
String jsonResponse = IOUtils.toString(new FileInputStream(jsonFileName));
NamedXContentRegistry registry = new NamedXContentRegistry(getDefaultNamedXContents());
XContentParser parser = JsonXContent.jsonXContent.createParser(registry, jsonResponse);
return SearchResponse.fromXContent(parser);
} catch (IOException e) {
throw new RuntimeException("Failed to get resource: " + jsonFileName, e);
} catch (Exception e) {
throw new RuntimeException(("exception " + e));
}
}
private static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(TopHitsAggregationBuilder.NAME, (parser, content) -> ParsedTopHits.fromXContent(parser, (String) content));
map.put(StringTerms.NAME, (parser, content) -> ParsedStringTerms.fromXContent(parser, (String) content));
map.put(SumAggregationBuilder.NAME, (parser, content) -> ParsedSum.fromXContent(parser, (String) content));
//map.put(ScriptedMetricAggregationBuilder.NAME, (parser, content) -> ParsedScriptedMetric.fromXContent(parser, (String) content));
List<NamedXContentRegistry.Entry> entries = map.entrySet()
.stream()
.map(entry -> new NamedXContentRegistry.Entry(Aggregation.class,
new ParseField(entry.getKey()),
entry.getValue()))
.collect(Collectors.toList());
return entries;
}
Parsed response with empty buckets (expectation is for the buckets to have aggregations totalCars and totalTrucks)
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 75,
"successful": 75,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 776329,
"max_score": 0,
"hits": []
},
"aggregations": {
"sterms#matched": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
}
}
I am not sure if sterms is the right type for the filter
The answer for what type needs to be used is 'filter' (filter#matched). And Java class counterpart is FilterAggregationBuilder
I have the following JSON text that I need to parse to get "id": 176514,
What is the required code?
{
"response": {
"count": 10307,
"items": [
{
"id": 176514,
"from_id": -114200945,
"owner_id": -114200945,
"date": 1506629224,
"marked_as_ads": 0,
"post_type": "post",
"text": "-я с разбитым сердцем сука,но я всё равно влюблённый.",
"post_source": {
"type": "api"
},
"comments": {
"count": 1,
"groups_can_post": true,
"can_post": 1
},
"likes": {
"count": 103,
"user_likes": 0,
"can_like": 1,
"can_publish": 1
},
"reposts": {
"count": 3,
"user_reposted": 0
},
"views": {
"count": 1022
}
}
]
}
}
I try some times but.. (
my code
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
class VK{
public static void main(String [] args) throws IOException{
URL url = new URL("my url which return JSON structure");
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
JSONObject obj = new JSONObject(str);
JSONObject res = obj.getJSONArray("items").getJSONObject(0);
System.out.println(res.getInt("id"));
}
}
Eclipse
my errors:
Exception in thread "main" org.json.JSONException: JSONObject["items"] not found.
at org.json.JSONObject.get(JSONObject.java:472)
at org.json.JSONObject.getJSONArray(JSONObject.java:619)
at VK.main(VK.java:26)
You need to go one more level deep.
JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));
try this:
JSONObject obj = new JSONObject(str);//assuming that obj is the same object as in the example
//to get the id
int id = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0).getInt("id");
In case that you are parsing Array of objects
JSONArray jsonArray = new JSONArray(stringToParse);
than continue as usual
I am having trouble parsing this particular JSONObject,
Here is the object:
{"status":1,"dds":{"id":1,"name":"DDS1","description":"This is DDS 1","children":[{"id":2,"order":1,"type":1,"children":[{"id":3,"order":1,"type":3,"children":[]},{"id":4,"order":2,"type":2,"children":[]}]}]}}
That object is stored in my variable called result, here is my code to parse it:
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonObj = new JSONObject(result);
jsonArr = jsonObj.getJSONArray("dds");
} catch (JSONException e) {
e.printStackTrace();
}
And it is giving me this error:
org.json.JSONException: Value {"id":1,"children":[{"type":1,"order":1,"id":2,"children":[{"type":3,"order":1,"id":3,"children":[]},{"type":2,"order":2,"id":4,"children":[]}]}],"description":"This is DDS 1","name":"DDS1"} at dds of type org.json.JSONObject cannot be converted to JSONArray
I am trying to break it up into sub arrays of children. Where am I going wrong?
#Mr Love
here is my output to your code
You are calling jsonArr = jsonObj.getJSONArray("dds");, however dds is not an array, it's a JSON object, if you format the JSON you can see it clearly:
{
"status":1,
"dds":{
"id":1,
"name":"DDS1",
"description":"This is DDS 1",
"children":[
{
"id":2,
"order":1,
"type":1,
"children":[
{
"id":3,
"order":1,
"type":3,
"children":[
]
},
{
"id":4,
"order":2,
"type":2,
"children":[
]
}
]
}
]
}
}
So you will just need to call JSONObject dds = jsonObj.getJSONObject("dds"), and if you want the children you would call JSONArray children = jsonObj.getJSONObject("dds").getJSONArray("children");.
private static final String json = "{\"status\":1,\"dds\":{\"id\":1,\"name\":\"DDS1\",\"description\":\"This is DDS 1\",\"children\":[{\"id\":2,\"order\":1,\"type\":1,\"children\":[{\"id\":3,\"order\":1,\"type\":3,\"children\":[]},{\"id\":4,\"order\":2,\"type\":2,\"children\":[]}]}]}}";
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject(json);
JSONObject dds = jsonObj.getJSONObject("dds");
JSONArray children = dds.getJSONArray("children");
System.out.println("Children:");
System.out.println(children.toString(4));
JSONArray grandChildren = children.getJSONObject(0).getJSONArray("children");
System.out.println("Grandchildren:");
System.out.println(grandChildren.toString(4));
}
Produces:
Children:
[{
"children": [
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
],
"id": 2,
"order": 1,
"type": 1
}]
Grandchildren:
[
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
]
You can do it like this, where the JsonElement could be a JSONobject or JsonArray or any primitive type:
private JsonElement findElementsChildren(JsonElement element, String id) {
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if(id.equals(jsonObject.get("id").getAsString())) {
return jsonObject.get("children");
} else {
return findElementsChildren(element.get("children").getAsJsonArray(), id);
}
} else if(element.isJsonArray()) {
JsonArray jsonArray = element.getAsJsonArray();
for (JsonElement childElement : jsonArray) {
JsonElement result = findElementsChildren(childElement, id);
if(result != null) {
return result;
}
}
}
return null;
}