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
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 currently received the json file in java, turned the json file on the formun, debugged it, and tried sysout.
The problem is, I try to output to the table in jsp, but only the last source from json comes out.
How can we solve this?
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
Map<String,String> map = new HashMap<String,String>();
List<Map<String,String>> spaghettiList = new ArrayList<Map<String,String>>();
for(int i = 0; i < pageCnt; i++) {
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
map.put("no", no);
map.put("name", name);
map.put("explanation", explanation);
spaghettiList.add(map);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
json
[
{
"no": "1",
"name": "Spaghettoni",
"explanation": "It is commonly used in the Carbonara Spaghetti, which is about 2mm thick."
},
{
"no": "2",
"name": "Spaghettini",
"explanation": "Spaghetti 1.6mm thick"
},
{
"no": "3",
"name": "Fedelini",
"explanation": "Spaghetti from 1.3mm to 1.5mm thick"
}]
you have to move this Map<String,String> map = new HashMap<String,String>(); inside your for loop.
Note:
As JB Nizet mentioned start using objects instead of JsonArray.
First thing first
Solve Issue
You are only getting last row in your JSP is because you have declared your Map outside of for loop.
If you are in hurry and have no time in world just move this
Map<String,String> map = new HashMap<String,String>();
inside
for(int i = 0; i < pageCnt; i++) {
This will solve your problem.
Improve your Code
But you can make it way more better and efficient by doing something like this
Define a DTO class
public class MyData {
private String no;
private String name;
private String explanation;
// getter setter
}
Use this DTO class to fill values like you did for Map
The whole code looks something like this.
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
List<MyData> spaghettiList = new ArrayList<MyData>();
for(int i = 0; i < pageCnt; i++) {
MyData mydata = new MyData();
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
mydata.setNo(no);
mydata.setName(name);
mydata.setExplanation(explanation);
spaghettiList.add(mydata);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
Can you please explain me where i am going wrong, am able to traverse each node but getting exceptions..
Have written code recursively to traverse through the jsonstring,
public static void main(String [] args) {
String jsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key+"==>"+value);
parse(value);
}
} catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**"+value);
parse(value);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
JSON string is a key value pairs and many libraries gives access to traverse through...
Here is one of the example.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
Find it really interesting here.
The same example, I have formatted the JSON string which you published,
public static void main(String[] args) {
String jsonString = "{\"developers\":[{\"firstName\":\"Linus\",\"lastName\":\"Torvalds\"},{\"firstName\":\"John\",\"lastName\":\"von Neumann\"}]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key + "==>" + value);
parse(value);
}
}
catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**" + value);
parse(value);
}
}
catch (JSONException e1) {
// e1.printStackTrace();
}
// e.printStackTrace();
}
}
Output:
developers==>[{"lastName":"Torvalds","firstName":"Linus"},{"lastName":"von Neumann","firstName":"John"}]
**{"lastName":"Torvalds","firstName":"Linus"}
lastName==>Torvalds
firstName==>Linus
**{"lastName":"von Neumann","firstName":"John"}
lastName==>von Neumann
firstName==>John
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");
Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}