Get JSON value and store it - java

Here is my JSON file, I need to take values from key : value pair and then thoose values to store into ArrayList rating to sort it, but with this code I just get "reviews" as the key ... Can you help me? I know to get all key : value pairs but i need just one pair and take value from it. Should I use Iterator, for each ? Can you give me some direction and example
{
"reviews": [
{
"id": 2097047,
"reviewId": "93f131be27dc1122bb7ef0048ad10e4f",
"reviewFullText": "5 star review",
"reviewText": "5 star review",
"numLikes": 0,
"numComments": 0,
"numShares": 0,
"rating": 5,
"reviewCreatedOn": "2 months ago",
"reviewCreatedOnDate": "2021-01-25T13:00:35+00:00",
"reviewCreatedOnTime": 1611579635,
"reviewerId": null,
"reviewerUrl": null,
"reviewerName": "Reviewer #20",
"reviewerEmail": null,
"sourceType": "custom",
"isVerified": false,
"source": "custom",
"sourceName": "1-20 Reviews",
"sourceId": "890cdd7974cdf8aabe6e9051f5a87303bdb933ae",
"tags": [],
"href": null,
"logoHref": null,
"photos": []
},
{
"id": 2097046,
"reviewId": "6e7bd4c71a56885ef583bd79186af689",
"reviewFullText": "4 star review",
"reviewText": "4 star review",
"numLikes": 0,
"numComments": 0,
"numShares": 0,
"rating": 4,
"reviewCreatedOn": "2 months ago",
"reviewCreatedOnDate": "2021-01-25T13:00:21+00:00",
"reviewCreatedOnTime": 1611579621,
"reviewerId": null,
"reviewerUrl": null,
"reviewerName": "Reviewer #19",
"reviewerEmail": null,
"sourceType": "custom",
"isVerified": false,
"source": "custom",
"sourceName": "1-20 Reviews",
"sourceId": "890cdd7974cdf8aabe6e9051f5a87303bdb933ae",
"tags": [],
"href": null,
"logoHref": null,
"photos": []
},
public class GetPair {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
ArrayList<Object> rating = new ArrayList<>();
Object obj = new JSONParser()
.parse(new FileReader("C:\\Users\\User\\eclipse-workspace\\Task\\files\\reviews.json"));
JSONObject jo = (JSONObject) obj;
for (Object key : jo.keySet()) {
String keys = (String) key;
Object keyObj = jo.get(keys);
if (!(keyObj instanceof JSONObject)) {
// System.out.println(keys + " " + keyObj);
}
rating.add(keys);
System.out.println(rating);
}
}
}

The main object only has one key: "reviews". Its value is an array. If you want to add each element of the array in the ArrayList, you can do something like this:
JSONObject jo = (JSONObject) obj;
JSONArray array = (JSONArray)jo.get("reviews");
for (int ix = 0; ix < array.size(); ++ix) {
JSONObject elm = (JSONObject)array.get(ix);
rating.add(elm);
System.out.println(rating);
}

Related

Finding user input in JSON file in Java

So I Have two JSON files like this:
FlightEntity
[
{
"flightId": 0,
"flightNumber": 6211,
"departureAirportIATACode": "ANC",
"arrivalAirportIATACode": "GDN",
"departureDate": "2015-06-16T03:20:34 -02:00"
},
{
"flightId": 1,
"flightNumber": 8293,
"departureAirportIATACode": "LAX",
"arrivalAirportIATACode": "MIT",
"departureDate": "2018-03-02T05:12:28 -01:00"
},
.
.
.
{
"flightId": 4,
"flightNumber": 1551,
"departureAirportIATACode": "SEA",
"arrivalAirportIATACode": "LEW",
"departureDate": "2018-01-11T10:48:16 -01:00"
}
]
Cargo Enity
[
{
"flightId": 0,
"baggage": [
{
"id": 0,
"weight": 494,
"weightUnit": "lb",
"pieces": 32
},
{
"id": 1,
"weight": 572,
"weightUnit": "lb",
"pieces": 951
},
{
"id": 2,
"weight": 520,
"weightUnit": "kg",
"pieces": 119
},
{
"id": 3,
"weight": 993,
"weightUnit": "kg",
"pieces": 672
},
{
"id": 4,
"weight": 318,
"weightUnit": "kg",
"pieces": 245
}
],
"cargo": [
{
"id": 0,
"weight": 885,
"weightUnit": "kg",
"pieces": 893
},
{
"id": 1,
"weight": 804,
"weightUnit": "kg",
"pieces": 407
},
{
"id": 2,
"weight": 388,
"weightUnit": "kg",
"pieces": 674
}
]
}
]
Now I want to get Cargo Weight for requested Flight. For example:
User Inputs flight number 6211.
I compare the input and take the right flightId from FlightEntity JSON file(in this example it's 0).
Then I find the corresponding flightId in Cargo Entity JSON file.
Print out the sum of cargo weight.
My problem is that I don't know how to find the input value(flight number) in the JSON array and then return corresponding flightId. Right now my code only takes input from user and print whole JSON file from Flight Entity.
package com.company;// Java program to read JSON from a file
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.parser.*;
import org.json.simple.parser.JSONParser;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Flight Number:");
int FlightNumber = myObj.nextInt() ; // Read user input
Scanner newObj = new Scanner(System.in);
System.out.println("Enter Flight Date(yyyy-mm-dd):");
String Date = newObj.nextLine();
System.out.println("Flight Number: " + FlightNumber);// Output user input
System.out.println("Flight Number: " + Date);// Output user input
Flight(FlightNumber, Date);
}
public static void Flight(int number, String date) throws IOException, ParseException {
// parsing file "CargoEntity.json"
Object obj = new JSONParser().parse(new FileReader("FlightEntity.json"));
// typecasting obj to JSONObject
JSONArray jo=(JSONArray)obj;
// getting Flight id for our number
//Iterating the contents of the array
for (Object o : jo) {
System.out.println(o);
}
}
}
You can get to the flightNumber and flightId by modifying your Flight function as follows:
for (Object o : jo) {
JSONObject flight = (JSONObject)o;
Long flightNumber = (Long)flight.get("flightNumber");
Long flightId = (Long)flight.get("flightId");
if (flightNumber.intValue() == number) {
System.out.println("corresponding flightId is: " + flightId);
}
}
Individual flight o is cast as JSONObject which allows accessing corresponding attributes via the get method.

How to sum json value after sorted in java android?

Following Json needs to group by city to get array along with count if city have same array value. after that I want to sort the 2 biggest and the rest are added together, but how to do it?
{
"data": [
{
"ID": 47,
"city": "Jakarta"
},
{
"ID": 48,
"city": "Bogor"
},
{
"ID": 49,
"city": "Bogor"
},
{
"ID": 50,
"city": "Jakarta"
},
{
"ID": 51,
"city": "Jakarta"
},
{
"ID": 52,
"city": "Bali"
},
{
"ID": 50,
"city": "Lampung"
}
]
}
and i have tried so far is group by city to get array
try {
JSONObject jsonObject = new JSONObject(result);
HashMap<String,Integer> hashMap = new HashMap<>();
for (int i=0;i<jsonObject.getJSONArray("data").length();i++){
JSONObject innerJsonObject = jsonObject.getJSONArray("data").getJSONObject(i);
String key = innerJsonObject.getString("city");
if(hashMap.containsKey(key)){
int count = hashMap.get(key)+1;
hashMap.put(key,count);
}else {
hashMap.put(key,1);
}
}
Log.e("Hashmap---",hashMap.toString());
} catch (JSONException e) {
e.printStackTrace();
}
and the result is :
Bogor = 2
Jakarta = 3
Bali = 1
Lampung = 1
the expected result is :
Jakarta = 3
Bogor = 2
Another city = 2
Try to add that HashMap into TreeMap after the for loop like this
Map<String, Integer> reverseSortedMap = new TreeMap<String,
Integer>(Collections.reverseOrder());
reverseSortedMap.putAll(hashMap);//your hashMap with count of city
System.out.println("Reverse Sorted Map : " + reverseSortedMap);

Remove numeric tags in dynamic json using java

I have a JSON Content in a String and sometimes it has numeric tags which has to be removed.
Below is a sample JSON content
{
"Test": {
"P1": false,
P2": {
"2000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"4000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"5000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"8000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"6000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
]
},
"P3": "XYZ",
"P4": ABC,
"VL": "",
"PL": [{
"start_date": 1496480880.0,
"id": "TEST1"
}
],
},
"PS": "AMD",
"links": [{
"LOC": "en-US",
"PS": "AMD"
}, {
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
In the above case "P2" tag has numeric keys and in such case we need to display it as after converting the string to JSON. Which means, we need to remove the tags which has numeric keys.
I have tried with org.json, org.json.simple and com.gson as well but nothing seems to work.
I am able to read each line using the below code snipet
public static void printJson(JsonElement jsonElement) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
try{
Integer.parseInt(en.getKey());
break;
}catch(NumberFormatException ex){
if("".equals(str)){
str = "\"" + en.getKey() + "\": {";
}else{
str = str + "\"" + en.getKey() + "\": {";
}
System.out.println(en.getKey() + "-----" + en.getValue());
}
printJson(en.getValue());
}
}
}
// Check whether jsonElement is Arrary or not
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
for (JsonElement je : jarr) {
printJson(je);
}
}
// Check whether jsonElement is NULL or not
else if (jsonElement.isJsonNull()) {
// print null
System.out.println("null");
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
if("".equals(str)){
str = "\"" + jsonElement.getAsString() + "\"";
}else{
str = str + "\"" + jsonElement.getAsString() + "\"";
}
System.out.println(jsonElement.getAsString());
}
}
But am unable to remove the numeric keyed tags. Can someone please help me with this.
If you want to strip JSONObject keys that are numeric, you can do it like this:
private static void strip(JSONObject obj) {
for (Iterator<String> keyIter = obj.keys(); keyIter.hasNext(); ) {
String key = keyIter.next();
if (key.matches("\\d+"))
keyIter.remove();
else
strip(obj.get(key));
}
}
private static void strip(Object value) {
if (value instanceof JSONObject) {
strip((JSONObject) value);
} else if (value instanceof JSONArray) {
for (Object elem : (JSONArray) value)
strip(elem);
}
}
Test
String input = new String(Files.readAllBytes(Paths.get("path/to/file.json")), StandardCharsets.US_ASCII);
JSONObject obj = new JSONObject(input);
strip(obj);
System.out.println(obj.toString(2));
Output
{
"PS": "AMD",
"Test": {
"P1": false,
"P2": {},
"P3": "XYZ",
"P4": "ABC",
"VL": "",
"PL": [{
"id": "TEST1",
"start_date": 1.49648088E9
}]
},
"links": [
{
"LOC": "en-US",
"PS": "AMD"
},
{
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
I got the solution with Andreas help.
But I had another issue while working on it. It was working fine for 2-3 levels only. After 3rd level, if there are any numeric keys, they were not being removed.
I have added one more condition to check if the object is an instance of org.json.JSONObject and then check if that JSONObject has any JSONArray.
Sample code given below
if (value instanceof org.json.JSONArray) {
for (int i=0; i< ((org.json.JSONArray) value).length(); i++) {
try{
if(((org.json.JSONArray) value).get(i).getClass().getName() =="org.json.JSONObject"){
strip((JSONObject) ((org.json.JSONArray) value).get(i));
}
}catch(Exception ex){
}
}
}

split all array elements from json in java

How to split all array elements from JSON in Java
{
"id": "405844",
"username": "abc8",
"password_hash": "dkjfhs7rjkds932dajk2900932",
"role": "customer",
"followed_stores" :
[
{
"id": "sda",
"created": {
"date": "2016-06-28 14: 43 : 28",
"epoch": 1467125008563
}
}
],
"followed_influencers": [
{
"id": "sda",
"created": {
"date": " 2016-06-28 14: 43 : 28",
"epoch": 1467125008563
}
}
]
}
I want 3 JSON in 2 json I must have followed_stores array, followed_influencer array and in the last remaining json
You can create an instance of org.json.JSONArray with server response:
String serverResponse = "YOUR STRING";
JSONArray serverJsonArray = new JSONArray(serverResponse);
And then fill products list:
ArrayList<String> products = new ArrayList<>(serverJsonArray.length());
for(int i = 0; i < serverJsonArray.length(); i++){
products.add(serverJsonArray.getString(i));
}
Or if you absolutely want a String array:
String[] products = new String[serverJsonArray.length()];
for(int i = 0; i < serverJsonArray.length(); i++){
products[i] = serverJsonArray.getString(i);
}

Parse large json data in Java with arrays and strings in json values

The json string generated from the media server looks like this
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"albums": [
{
"albumid": 1,
"albumlabel": "",
"artist": [
"www.SongsLover.pk"
],
"artistid": [
2
],
"description": "",
"genre": [
"Pop"
],
"label": "Single 2012",
"rating": 0,
"style": [
""
],
"thumbnail": "image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fbackup%20Music%2fSissle2%2fGangnam%20Style%20.mp3/",
"title": "Single 2012",
"type": "",
"year": 0
},
{
"albumid": 164,
"albumlabel": "",
"artist": [
"ARrahman","MJ"
],
"artistid": [
146,163
],
"description": "",
"genre": [
"Soundtrack"
],
"label": "Lord of the rings",
"rating": 0,
"style": [
""
],
"thumbnail": "image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fExtras_Test%2fEnakkena%20Yenave.mp3/",
"title": "Lord of the rings",
"type": "",
"year": 2000
},{..........},{........},{........}
],
"limits": {
"end": 155,
"start": 0,
"total": 155
}
}
}
The following is the code i tried using Java. Iam getting the json response as Input stream and using jsonreader to parse the json response. But here in the above json, the artist dictionary has array values without names.
JsonReader reader = new JsonReader(new InputStreamReader(inputStream,
"UTF-8"));
ArrayList<Integer> albumId = new ArrayList<Integer>();
ArrayList<String> artistId = new ArrayList<String>();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equalsIgnoreCase("result")) {
reader.beginObject();
while (reader.hasNext()) {
String check = reader.nextName();
if (check.equalsIgnoreCase(type)) {
reader.beginArray();
int i = 0;
while (reader.hasNext()) {
i++;
reader.beginObject();
int albumid;
String artistid = null;
while (reader.hasNext()) {
name = reader.nextName();
if (name.equalsIgnoreCase("albumid")) {
albumid = reader.nextInt();
albumId.add(albumid);
} else if (name
.equalsIgnoreCase("artist")) {
reader.beginArray();
while(reader.hasNext()){
artistid = reader.nextString();
artistId.add(artistid);
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
//}
}
Log.i(LOGCAT, Integer.toString(i));
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
} else {
reader.skipValue();
}
}
reader.endObject();
So, the problem for me is how to get the array values from the artist dictionary with the above code. Please help me in this. Thanks in advance.
// Try this way,hope this will you to solve your problem...
String respone = "{\"id\":1,\"jsonrpc\":\"2.0\",\"result\":{\"albums\":[{\"albumid\":1,\"albumlabel\":\"\",\"artist\":[\"www.SongsLover.pk\"],\"artistid\":[2],\"description\":\"\",\"genre\":[\"Pop\"],\"label\":\"Single 2012\",\"rating\":0,\"style\":[\"\"],\"thumbnail\":\"image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fbackup%20Music%2fSissle2%2fGangnam%20Style%20.mp3/\",\"title\":\"Single 2012\",\"type\":\"\",\"year\":0},{\"albumid\":164,\"albumlabel\":\"\",\"artist\":[\"ARrahman\",\"MJ\"],\"artistid\":[146,163],\"description\":\"\",\"genre\":[\"Soundtrack\"],\"label\":\"Lord of the rings\",\"rating\":0,\"style\":[\"\"],\"thumbnail\":\"image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fExtras_Test%2fEnakkena%20Yenave.mp3/\",\"title\":\"Lord of the rings\",\"type\":\"\",\"year\":2000}],\"limits\":{\"end\":155,\"start\":0,\"total\":155}}}";
ArrayList<HashMap<String,Object>> albumList = new ArrayList<HashMap<String, Object>>();
try{
JSONObject responseJson = new JSONObject(respone);
JSONArray albumJsonArray = responseJson.getJSONObject("result").getJSONArray("albums");
for (int i=0;i<albumJsonArray.length();i++){
HashMap<String,Object> album = new HashMap<String, Object>();
album.put("albumid",albumJsonArray.getJSONObject(i).getString("albumid"));
album.put("albumlabel",albumJsonArray.getJSONObject(i).getString("albumlabel"));
JSONArray artistJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("artist"));
ArrayList<String> artistList = new ArrayList<String>();
for (int j=0;j<artistJsonArray.length();j++){
artistList.add(artistJsonArray.getString(j));
}
album.put("artist",artistList);
JSONArray artistidJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("artistid"));
ArrayList<String> artistidList = new ArrayList<String>();
for (int j=0;j<artistidJsonArray.length();j++){
artistidList.add(artistidJsonArray.getString(j));
}
album.put("artistid",artistidList);
album.put("description",albumJsonArray.getJSONObject(i).getString("description"));
JSONArray genreJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("genre"));
ArrayList<String> genreList = new ArrayList<String>();
for (int j=0;j<genreJsonArray.length();j++){
genreList.add(genreJsonArray.getString(j));
}
album.put("genre",genreList);
album.put("label",albumJsonArray.getJSONObject(i).getString("label"));
album.put("rating",albumJsonArray.getJSONObject(i).getString("rating"));
JSONArray styleJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("style"));
ArrayList<String> styleList = new ArrayList<String>();
for (int j=0;j<styleJsonArray.length();j++){
styleList.add(styleJsonArray.getString(j));
}
album.put("style",styleList);
album.put("thumbnail",albumJsonArray.getJSONObject(i).getString("thumbnail"));
album.put("title",albumJsonArray.getJSONObject(i).getString("title"));
album.put("type",albumJsonArray.getJSONObject(i).getString("type"));
album.put("year",albumJsonArray.getJSONObject(i).getString("year"));
albumList.add(album);
}
for (HashMap<String,Object> album:albumList){
System.out.println("Album Id : "+album.get("albumid").toString());
System.out.println("Album Label : "+album.get("albumlabel").toString());
System.out.println("Album Description : "+album.get("description").toString());
System.out.println("Label : "+album.get("label").toString());
System.out.println("Rating : "+album.get("rating").toString());
System.out.println("Thumbnail : "+album.get("thumbnail").toString());
System.out.println("Title : "+album.get("title").toString());
System.out.println("Type : "+album.get("type").toString());
System.out.println("Year : "+album.get("year").toString());
System.out.println("Artist size : "+((ArrayList<String>)album.get("artist")).size());
System.out.println("Artist Id size : "+((ArrayList<String>)album.get("artistid")).size());
System.out.println("Genre size : "+((ArrayList<String>)album.get("genre")).size());
System.out.println("Style size : "+((ArrayList<String>)album.get("style")).size());
}
}catch (Throwable e){
e.printStackTrace();
}
You can use JsonPath to extract the artist arrays.
e.g. "$.result.albums[*].artist".
JsonSurfer would be a good choice if you are handling large json because it uses streaming parser without loading whole json into the memory.
The code is short with JsonSurfer.
JsonSurfer jsonSurfer = JsonSurfer.gson();
Collection<Object> result = jsonSurfer.collectAll(inputStreamReader, "$.result.albums[*].artist");

Categories