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.
Related
I have a problem always i call the method addplayers he inserts into the jsonfile the array required, but, he always create new key , so, i'm trying to insert a new player in the key Players always i create a new player.
I created some conditions for that but is not working, like parsing the file and check the key.
the expecteded result:
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
the result at moment:
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
The Method
public void addPlayer(PlayerManager playerManager) {
if (file.exists()) {
System.out.println("FODASEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
try {
PrintStream printStream = new PrintStream(new FileOutputStream("data.json",true));
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
ArrayUnorderedList<Players> dataplayer = playerManager.getPlayersList();
try {
jsonObject = (JSONObject) new JSONParser().parse(new FileReader(file));
jsonArray = (JSONArray) jsonObject.get("players");
} catch (ParseException e) {
// Caso não exista, cria um novo objeto JSON com a chave "players"
jsonArray = new JSONArray();
}
Set<String> keys = new HashSet<>();
if (jsonObject.containsKey("players")) {
keys.add("players");
}
if (!keys.contains("players")) {
jsonArray = new JSONArray();
jsonObject.put("players", jsonArray);
} else {
jsonArray = (JSONArray) jsonObject.get("players");
}
for (Players player : dataplayer) {
JSONObject playerObject = new JSONObject();
playerObject.put("name", player.getName());
playerObject.put("team", player.getTeam().toString());
playerObject.put("level", player.getLevel());
playerObject.put("experiencePoints", player.getExperiencePoints());
playerObject.put("current_Energy", player.getCurrentEnergy());
jsonArray.add(playerObject);
}
printStream.println(jsonObject);
printStream.flush();
printStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At a glance the problem seems to be that you're reading and changing the same file, which you have open in append mode:
PrintStream printStream = new PrintStream(new FileOutputStream("data.json",true));
The true parameter there means whatever you write on that file will be appended at the end when you write to it, which seems compatible with the behaviour you're seeing.
Depending on what you need to achieve, you might prefer to just write on a different file as output.
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);
}
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);
I am writing a java program to read Json as associative array, like we do in javascript and PHP. I am 90% done but problem occurs when i try to read array from Json object.
Here is data.json file which contains student record
{
"students": {
"2334": {
"name": {
"firstname": "umer",
"lastname": "farooq"
},
"subject": {
"marks": {
"maths": {
"total": 100.0,
"obtained": 70.0
},
"computer": {
"total": 100.0,
"obtained": 96.0
}
}
},
"lang": ["java", "javascript", "C#"]
},
"1003": {
"name": {
"firstname": "yasir",
"lastname": "khan"
},
"subject": {
"marks": {
"maths": {
"total": 100.0,
"obtained": 80.0
},
"computer": {
"total": 100.0,
"obtained": 60.0
}
}
},
"lang": ["C++", "PHP", "C#"]
},
"1233": {
"name": {
"firstname": "Mubarak",
"lastname": "Amin"
},
"subject": {
"marks": {
"maths": {
"total": 100.0,
"obtained": 70.0
},
"computer": {
"total": 100.0,
"obtained": 50.0
}
}
},
"lang": ["Ruby", "javascript", "C"]
}
}
}
To fetch marks obtained by student with the id 1233 in mathematics, i would simple pass string ['students']['1233']['subject']['marks']['maths']['obtained'] to getValue() method
JSONAssociativeArrayReader parser = new JSONAssociativeArrayReader();
parser.setJSONFile(new File("data.json"));
double marksObtainedInMaths = (double) parser.getValue("['students']['1233']['subject']['marks']['maths']['obtained']");
System.out.println("Marks obtained (maths) = " + marksObtainedInMaths);
Above code produces Marks obtained (maths) = 70.0 which is correct. Problem occurs when i try to fetch array from Json file via my getArray() method.
System.out.println("languages = " + parser.getArray("['students']['1233']['lang']") );
expected output : languages = [Ruby, javascript, C]
Following error occurs when above statement is executed
Exception in thread "main" javax.script.ScriptException: TypeError: Cannot read property "lang" from undefined in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:451)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:403)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(Unknown Source)
at JSONAssociativeArrayReader.getArray(Main.java:77)
at Main.main(Main.java:30)
Caused by: <eval>:1 TypeError: Cannot read property "lang" from undefined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:213)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:185)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:172)
at jdk.nashorn.internal.runtime.Undefined.get(Undefined.java:157)
at jdk.nashorn.internal.scripts.Script$2$\^eval\_.:program(<eval>:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:446)
... 6 more
Here is the code for JSONAssociativeArrayReader
class JSONAssociativeArrayReader
{
private ScriptEngineManager factory;
private ScriptEngine engine;
private static final String JSON_OBJECT_NAME = "jsonObject";
private static final String JSON_ARRAY_NAME = "jsonArray";
public JSONAssociativeArrayReader() throws ScriptException
{
factory = new ScriptEngineManager();
engine = factory.getEngineByName("JavaScript");
}
public void setJSONFile(File jsonFile) throws IOException, ScriptException
{
String jsonStringFromFile = "";
if(jsonFile != null)
{
BufferedReader br = new BufferedReader(new FileReader(jsonFile));
String line = "";
while((line = br.readLine()) != null)
{
jsonStringFromFile += line;
}
}
engine.eval("var " + JSON_OBJECT_NAME + " = " + jsonStringFromFile);
}
public ArrayList<Object> getArray(String associativeArray) throws ScriptException
{
ArrayList<Object> objects = new ArrayList<>();
engine.eval("var " + JSON_ARRAY_NAME + " = " + associativeArray);
engine.eval("var arraylength = " + JSON_ARRAY_NAME + ".length");
int arrayLength = (int) engine.eval("arraylength");
for (int i = 0; i < arrayLength; i++)
{
engine.eval(" var arrayElement = " + JSON_ARRAY_NAME + "["+i+"]");
objects.add(engine.get("arrayElement"));
}
return objects;
}
public Object getValue(String associativeArray) throws ScriptException
{
return engine.eval(JSON_OBJECT_NAME+associativeArray);
}
}
What i am doing wrong ?
As far as I can tell, your issue is at
JSON_ARRAY_NAME + " = " + associativeArray);
You're forgetting the JSON_OBJECT_NAME and just assigning a var to the value of "['students']['1233']['lang']"
In other words, it needs to come to the result of
jsonObject['students']['1233']['lang']
However, in almost all JSON parsing libraries in Java, you would do something like
jsonObject.getObject("students")
.getObject("1233")
.getArray("lang")
Or using Gson/Jackson, you could easily write a model to implement
jsonObject.getStudent("1233").getLanguages()
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);
}