I was wondering already having an existing .json file how can I add more information to it without having to delete it and write it again. For now I have this code, but I cannot add new information to it.
public static void main( String[] args )
{
//First Employee
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Lokesh");
employeeDetails.put("lastName", "Gupta");
employeeDetails.put("website", "howtodoinjava.com");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
//Second Employee
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Brian");
employeeDetails2.put("lastName", "Schultz");
employeeDetails2.put("website", "example.com");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try (FileWriter file = new FileWriter("employees.json")) {
file.write(employeeList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I am trying to extract the below data from the json file and convert it in to csv file. however when i try to read the json file I am getting error as "Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
Required Fields
1.AssessmentID
2.AssessmentName
3.AccountName
4.AssetName
5.ApplicationName
6.AccountType
7.environment
JSON I recieve from application
[
{
"assessmentID":154,
"assesmentName":"TestApp _50553_WEB_CLIENT_08-02-2021 17:02:22",
"assessmentAccounts":
[{"accountName":"a.pss.apitest","assetName":"TestApp01","applicationName":"TestApp","accountType":"scbdev.net","environment":"Test"},
{"accountName":"1562081","assetName":"TestApp02","applicationName":"TestApp05","accountType":"LocalAccount","environment":"Test"}]
},
{
"assessmentID":155,
"assesmentName":"TestApp _50553_WEB_CLIENT_08-02-2021 17:19:39",
"assessmentAccounts":
[
{"accountName":"a.pss.apitest","assetName":"TestApp","applicationName":"TestApp03","accountType":"scbdev.net","environment":"Test"},
{"accountName":"1562081","assetName":"TestApp","applicationName":"TestApp04","accountType":"LocalAccount","environment":"Test"}
]}
]
MyCode:
public static void main(String args[]) {
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("C:\\Users\\1451615\\genie-projects\\AppOnboarding\\src\\test\\resources\\features\\appdata.json"))
{
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray AppAssessmentData = (JSONArray) obj;
System.out.println(AppAssessmentData);
AppAssessmentData.forEach( account -> parseAccountObject((JSONObject) account) );
}
catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private static void parseAccountObject(JSONObject account) {
//Get assessment accounts
JSONObject Assessment_Account = (JSONObject) account.get("assessmentAccounts");
//Get accountname
JSONObject account_Name = (JSONObject) account.get( "accountName" );
//Get assetname
JSONObject asset_Name = (JSONObject) account.get( "assetName" );
//Get applicationname
JSONObject application_name = (JSONObject) account.get( "applicationName" );
}
I want to create a JSON array structure like this or append an object to the structure
{ "user" : [
{"name" : "user1", "email": "user1#gmail"},
{"name": "user2", "email": "user2#gmail"}
]
}
I'm using GSON to write this into a file
public void appendToObject(File jsonFile, String key, String value) {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}
Here's the code with suggestions integrated and with reading and writing JSON file functions
but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}
how to structure it so that I get the desired output
I omitted some your code in appendToObject. But the meaning should be clear.
public void appendToObject(File jsonFile, String key, String value) {
...
JsonObject node = readOrCreateNew(jsonFile);
JsonObject newUser = user(key, value);
JsonElement user = node.get("user");
if (user != null && user.isJsonArray()){
((JsonArray) user).add(newUser);
} else {
JsonObject root = new JsonObject();
node.add("user", createArray(newUser));
}
...
}
private JsonObject createUserArray(JsonObject ... objects){
JsonArray userArray = new JsonArray();
for (JsonObject user : objects) {
userArray.add(user);
}
return userArray;
}
private JsonObject user(String email, String name){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
jsonObject.addProperty("email", email);
return jsonObject;
}
I am developing a java application in android studio and a Rest web server in java, netbeans.
I need to send a JSON to the server ...
I did the whole engine the webService and tested it using Postman.
The Json used was this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":[
{
"idAvaliacao":1,
"nota":5,
"observacao":"testeTEste"
},
{
"idAvaliacao":2,
"nota":4,
"observacao":"testeTEste"
}
]
}
Worked perfectly.
So I went to generate Json dynamically in the application:
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", PrincipalActivity.ticket_id);
for(int i=0; i < PrincipalActivity.listAval.size();i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", listAval.get(i).getId());
avaliacao.put("nota", listAval.get(i).getNota());
avaliacao.put("observacao", listAval.get(i).getObservacoes());
avaliacoes.add(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
} catch (JSONException e) {
e.printStackTrace();
}
}
The generated Json is this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":"[
{
\"idAvaliacao\":1,
\"nota\":5,
\"observacao\":\"testeTEste\"
},
{
\"idAvaliacao\":2,
\"nota\":4,\"observacao\":\"testeTEste\"
}
]"
}
If I use this second Json on Postman the webService no gets it correctly.
Get the id and the ticket, but the evaluations array gets a single item(avaliacoes.get(0)) = null.
I've looked at other posts about Json and ArrayJsons and nothing helped me ...
Parsing JSON Object in Java
Convert JsonObject to String
How to create correct JSONArray in Java using JSONObject
https://pt.stackoverflow.com/questions/140442/reconhecer-um-jsonobject-ou-jsonarray
Just replace avaliacoes.add(avaliacao); with avaliacoes.put(avaliacao);
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", "DemoActivity.ticket_id");
for(int i=0; i < 2;i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", "1");
avaliacao.put("nota", "nota");
avaliacao.put("observacao", "observacao");
avaliacoes.put(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
Log.d("DEMO", obj.toString()); // {"id":0,"ticket":"DemoActivity.ticket_id","avaliacoes":[{"idAvaliacao":"1","nota":"nota","observacao":"observacao"},{"idAvaliacao":"1","nota":"nota","observacao":"observacao"}]}
} catch (JSONException e) {
e.printStackTrace();
}
}
For best practice use Gson
I have a josn like this.From this how can i retrive platfrom and version values using java
code
public static void main(String[] args)
throws org.json.simple.parser.ParseException {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
josn
{
"France24":[
{
"platform":"Linux",
"version":"12.3",
}
],
"Seloger":[
{
"platform":"windows",
"version":"8",
}
],
"Marmiton":[
{
"platform":"mac",
"version":"10.1",
}
]
}
List<String> platformLst = new ArrayList<String>();
List<String> versionLst = new ArrayList<String>();
JSONArray array = obj.getJSONArray("France24");
for(int i = 0 ; i < array.length() ; i++){
JSONObject obj = array.getJSONObject(i);
versionLst.add(obj.getString("platform"));
platformLst .add(obj.getString("version"));
}
Existing Question
Example
Simple Json Tutorial Link
JSONArray jArray = jsonObject.getJSONArray("France24");
JSONObject france24Object = jArray.get(0);
String platform = france24Object.getString("platform");
String version = france24Object.getString("version");
Similarly, replace France24 with Seloger and Marmiton and repeat.
Like that:
JSONObject france = jsonObject.getJsonArray("France24").getJsonObject(0);
String platform = france.getString("platform");
String version = france.getString("version");
I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.
Below is my function code snippet:
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
I tried To convert into json by using this code but it is giving type mismatch error as function is of type List...
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
return jsonCartList;
}
Please help me resolve this.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
Try like below with Gson Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
if response is of type List , res.toString() is simply enough to convert to json or else we need to use
ObjectMapper mapper = new ObjectMapper();
String jsonRes = mapper.writeValueAsString(res);