Reading JSON File and Writing to csv - java

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" );
}

Related

Java: How do I create this JSON Array Structure using GSON

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;
}

How can I add data to a JSON on Java?

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();
}
}

How to parse a json file into a json object in java

I am trying to parse a json file in java. However I keep receiving an error.
This is the file I am trying to parse:
[{
"name": "John Smith",
"totalSales": 250,
"salesPeriod": 10,
"experienceMultiplier": 0.5
},
{
"name": "David Prowless",
"totalSales": 250,
"salesPeriod": 10,
"experienceMultiplier": 0.5
}
]
This is what I have tried:
public static void main(String[] args)
{
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String totalSales = (String) jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
This is the error I receive:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at mentormate.json.MentormateJson.main(MentormateJson.java:23)
Java Result: 1
I apologize if this is a silly question with a simple solution. I am new to json.
EDIT:
I have decided to go along with the code below. However, I cannot set the for each loop right to iterate through object in the json file.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for ( JSONObject jsonObject : jsonObjects) {
String name = (String) jsonObject.get("name");
System.out.println(name);
String totalSales = (String) jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
FINAL EDIT (PROBLEM SOLVED):
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for (Object o : jsonObjects) {
JSONObject jsonObject = (JSONObject) o;
String name = (String) jsonObject.get("name");
System.out.println(name);
Long totalSales = (Long) jsonObject.get("totalSales");
System.out.println(totalSales);
Long salesPeriod = (Long) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
Double exp = (Double) jsonObject.get("experienceMultiplier");
System.out.println(exp);
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Please try this:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for (Object o : jsonObjects) {
JSONObject jsonObject = (JSONObject) o;
String name = (String) jsonObject.get("name");
System.out.println(name);
Long totalSales = (Long)jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Your data contains a JSON array, not a JSON object.
Change the line
JSONObject jsonObject = (JSONObject) obj;
to
JSONArray jsonArray = (JSONArray) obj;
This array will contain two JSONObjects.
you can use alibaba's fastjson.You can download fastjson jar file,this is pom xml:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
when you import this jar,you can code like this:
import com.alibaba.fastjson.JSONObject;
import java.util.List;
public class MainTest {
public static void main(String[] args) {
String json = "[\n" +
"{\n" +
"\"name\": \"John Smith\",\n" +
"\"totalSales\": 250,\n" +
"\"salesPeriod\": 10,\n" +
"\"experienceMultiplier\": 0.5\n" +
"},\n" +
"{\n" +
"\"name\": \"David Prowless\",\n" +
"\"totalSales\": 250,\n" +
"\"salesPeriod\": 10,\n" +
"\"experienceMultiplier\": 0.5\n" +
"}\n" +
"]";
List<JSONObject> jsonObjects = JSONObject.parseArray(json,JSONObject.class);
jsonObjects.stream().forEach(System.out::print);
}
}
Please find whole example below.
1) Create DTO class with your params like,
class JsonParam {
private String name;
private int totalSales;
private int salesPeriod;
private float experienceMultiplier;
//Getter and setters
}
2) Then add Gson jar with min. version (2.2.4) - get online, or add dependency for maven structure.
3) Finally, add 2 lines in your code to get any parameter like,
List<JsonParam> jsonParams = new Gson().fromJson(json, new TypeToken<List<JsonParam>>() {}.getType());
System.out.println(jsonParams.get(0).getName());
In above statement, I have used 0 index, you can use for-loop as per your requirement.
try {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("./test.json"));
// parsing the JSON string inside the file that we created earlier.
JSONArray jsonarray = (JSONArray) obj;
for (int i = 0; i < jsonarray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonarray.get(i);
String name = (String) jsonObject.get("name");
System.out.println(name);
long totalSales = (long) jsonObject.get("totalSales");
System.out.println(totalSales);
long salesPeriod = (long) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
Double exp = (Double) jsonObject.get("experienceMultiplier");
System.out.println(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
Try this one

Java - Get multiple JSON values and turn into String

How would I get all the "name" values and turn them into a String?
So for example if I'd do the following:
System.out.println(value[1]);
It would print out name1.
Here is what I have so far:
JSON:
[
{
"name":"name1"
},
{
"name":"name2",
"changedToAt":1470659096000
},
{
"name":"name3",
"changedToAt":1473435817000
}
]
Java code:
try {
String UUID = p.getUniqueId().toString();
String slimUUID = UUID.replace("-", "");
InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();
String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
try {
JSONParser parser = new JSONParser();
JSONObject jsonparse = (JSONObject) parser.parse(json);
//get "name" values and turn into String
} catch (ParseException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You need to iterate over array and accumulate all name values into array of Strings.
So below is working source code:
JsonArray jsonObject = new JsonParser()
.parse(json)
.getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"
Using the URL from your comment and Java 8 Stream API I've built this main method:
public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
final InputStream in = new URL(url).openStream();
final String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
final JSONParser parser = new JSONParser();
final JSONArray jsonparse = (JSONArray) parser.parse(json);
System.out.println(jsonparse);
System.out.println();
final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
final JSONObject object = (JSONObject) obj;
return (String) object.getOrDefault("name", "");
}).peek(System.out::println).collect(Collectors.toList());
}
Try My library: abacus-common. All the above can be replaced with:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());
By the way, if slimUUID is equal to: UUID.randomUUID().toString().replaceAll("-", ""). It's be simplified:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

parse json values using java json parser

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");

Categories