I have difficulty printing java json data - java

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

Related

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

I can't loop through JSON Array for next Array

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

How to modify values of JsonObject / JsonArray directly?

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

Categories