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");
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 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
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";
}
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());
I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}