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.
Related
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);
}
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.
So I have an JSON data which looks like this. But I need to invert in one specific scene and one specific element ("iCalstate") its state.
For example if its true, it should overwrite it false. After it has overwritten the specific element it should write this json type to an file called test.json.
{"scene": [
{
"id": 0,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
},
{
"id": 1,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
},
{
"id": 2,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
}
]}
What I tried so far:
I have made methods to get the JSONObject & JSONArrays, I tried to create an if which does invert the value (it works). The thing that I didn't manage is to invert it on a specific sceneindex and elemindex --> any help would be gladly appreciated
int sceneindex = 0;
int elemindex = 0;
JSONObject json = new JSONObject();
JSONArray scene = new JSONArray();
JSONArray element = new JSONArray();
JSONArray relement = datain.getIcalSettingsElement(sceneindex); //gets the element from the "olf"
try {
for (int i = 0; i < 1; i++) {
json.put("scene", scene);
JSONObject node = new JSONObject();
scene.put(node);
node.put("id", i);
node.put("element", element);
}
for (int ii = 0; ii < 3; ii++) {
if (ii == elemindex) {
JSONObject enode = new JSONObject();
String invwrite = "";
if (relement.getJSONObject(ii).getString("iCalstate").equals("true")) {
invwrite = "false";
} else if (relement.getJSONObject(ii).getString("iCalstate").equals("false")) {
invwrite = "true";
}
enode.put("iCalstate", invwrite);
element.put(enode);
} else {
JSONObject enode = new JSONObject();
String write = relement.getJSONObject(ii).getString("iCalstate");
enode.put("iCalstate", write);
element.put(enode);
}
}
instead i am getting this it should only write at the first element, where the id is 0, but it's writing to each element:
{"scene": [
{
"id": 0,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
},
{
"id": 1,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
},
{
"id": 2,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
}
]}
Create a corresponding POJO for your JSON. And use ObjectMapper to map the JSON string and create an instance. You could then perform your desired operation on that instance.
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);
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I used the code to get a Jsonarray
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
The a json array like this code bellow. How can I get individual value of ratings.
[{
"rating": 3,
"documentId": "TRECCS-00674898-160",
"tags": ["Romantic", "Seafood", "Family Friendly"]
}, {
"rating": 2,
"documentId": "TRECCS-00247656-160",
"tags": ["Bar-hopping"]
}, {
"rating": 3,
"documentId": "TRECCS-00085961-160",
"tags": ["Gourmet Food"]
}, {
"rating": 4,
"documentId": "TRECCS-00086637-160",
"tags": ["Family Friendly", "Local Food", "Entertainment"]
}, {
"rating": 4,
"documentId": "TRECCS-00086308-160",
"tags": ["Family Friendly", "Tourism"]
}, {
"rating": 4,
"documentId": "TRECCS-00086622-160",
"tags": ["Healthy Food", "Romantic", "Gourmet Food"]
}, {
"rating": 2,
"documentId": "TRECCS-00809111-160",
"tags": ["Wellness", "Family Friendly", "Sport"]
}, {
"rating": 4,
"documentId": "TRECCS-00086310-160",
"tags": ["Family Friendly", "Sport"]
}, {
"rating": 4,
"documentId": "TRECCS-00340169-160",
"tags": ["Fashion Bargains", "Live Music", "Shopping for accessories", "Family Friendly"]
}, {
"rating": 4,
"documentId": "TRECCS-00018110-160",
"tags": ["Healthy Food", "Family Friendly", "Local Food", "Organic Food"]
}, {
"rating": 2,
"documentId": "TRECCS-00085880-160",
"tags": ["Romantic", "Sailing", "Seafood"]
}, {
"rating": 4,
"documentId": "TRECCS-00259825-152",
"tags": ["Family Friendly", "Budget Friendly"]
}]
Use this:
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
List<Integer> ratings = new ArrayList<>();
for(int i = 0; i < preferenceobj.length(); i++) {
JSONObject obj = preferenceobj.getJSONObject(i);
int rating = obj.getInt("rating"); // Your rating
ratings.add(rating);
}
// Show ratings
for(Integer rating : ratings) {
System.out.println(rating);
}
The answer I solved using the prvious comment of Srarta is:
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
List<Long> ratings = new ArrayList<>();
for(int i = 0; i < preferenceobj.size(); i++) {
JSONObject obj1 = (JSONObject) preferenceobj.get(i);
Long rating = (Long)obj1.get("rating");
ratings.add(rating);
}
// Show ratings
for(Long rating : ratings) {
System.out.println(rating);
}