Saya ingin membaca JSON
file ini dengan java menggunakan json simple library.
JSON
File saya terlihat seperti ini:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Ini adalah kode java yang saya tulis untuk membaca file ini:
package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\file.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Tapi saya mendapatkan pengecualian berikut:
Pengecualian di utas "main" java.lang.ClassCastException: org.json.simple.JSONArray tidak dapat ditransmisikan ke org.json.simple.JSONObject di javaapplication1.JavaApplication1.main (JavaApplication1.java:24)
Bisakah seseorang memberi tahu saya apa yang saya lakukan salah? Seluruh file adalah array dan ada objek dan array lain (mobil) di seluruh array file. Tapi saya tidak tahu bagaimana saya bisa mengurai seluruh array menjadi array java. Saya berharap seseorang dapat membantu saya dengan baris kode yang saya lewatkan dalam kode saya.
Terima kasih
sumber
a.get(0)
) karena itu yang paling cocok dengan kode asli Anda. Dokumentasi json-sederhana mengatakanJSONArray
adalahjava.util.List
, sehingga Anda dapat iterate atas unsur-unsur seperti kamu akan daftar normal. Apakah itu cukup untuk dilanjutkan?parser
dari perpustakaan mana (impor) itu?Anda dapat menggunakan perpustakaan jackson dan cukup menggunakan 3 baris ini untuk mengonversi file json Anda ke Objek Java.
ObjectMapper mapper = new ObjectMapper(); InputStream is = Test.class.getResourceAsStream("/test.json"); testObj = mapper.readValue(is, Test.class);
sumber
import com.fasterxml.jackson.databind.ObjectMapper;
Tambahkan Jackson databind:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0.pr2</version> </dependency>
Buat kelas DTO dengan bidang terkait dan baca file JSON:
ObjectMapper objectMapper = new ObjectMapper(); ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
sumber
Membaca dari JsonFile
public static ArrayList<Employee> readFromJsonFile(String fileName){ ArrayList<Employee> result = new ArrayList<Employee>(); try{ String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8); JSONObject obj = new JSONObject(text); JSONArray arr = obj.getJSONArray("employees"); for(int i = 0; i < arr.length(); i++){ String name = arr.getJSONObject(i).getString("name"); short salary = Short.parseShort(arr.getJSONObject(i).getString("salary")); String position = arr.getJSONObject(i).getString("position"); byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company")); if (position.compareToIgnoreCase("manager") == 0){ result.add(new Manager(name, salary, position, years_in_company)); } else{ result.add(new OrdinaryEmployee(name, salary, position, years_in_company)); } } } catch(Exception ex){ System.out.println(ex.toString()); } return result; }
sumber
Anda dapat menggunakan Gson untuk ini.
GSON
adalah pustaka Java yang dapat digunakan untuk mengubah Objek Java menjadiJSON
representasi mereka . Ini juga dapat digunakan untuk mengonversiJSON
string menjadi objek Java yang setara.Lihatlah Konversi JSON ke Java ini
sumber
Gunakan perpustakaan google-simple.
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>
Temukan kode contoh di bawah ini:
public static void main(String[] args) { try { JSONParser parser = new JSONParser(); //Use JSONObject for simple JSON and JSONArray for array of JSON. JSONObject data = (JSONObject) parser.parse( new FileReader("/resources/config.json"));//path to the JSON file. String json = data.toJSONString(); } catch (IOException | ParseException e) { e.printStackTrace(); } }
Gunakan JSONObject untuk JSON sederhana seperti
{"id":"1","name":"ankur"}
dan JSONArray untuk array seperti JSON[{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}]
.sumber
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Delete_01 { public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { JSONParser parser = new JSONParser(); JSONArray jsonArray = (JSONArray) parser.parse(new FileReader( "delete_01.json")); for (Object o : jsonArray) { JSONObject person = (JSONObject) o; String strName = (String) person.get("name"); System.out.println("Name::::" + strName); String strCity = (String) person.get("city"); System.out.println("City::::" + strCity); JSONArray arrays = (JSONArray) person.get("cars"); for (Object object : arrays) { System.out.println("cars::::" + object); } String strJob = (String) person.get("job"); System.out.println("Job::::" + strJob); System.out.println(); } } }
sumber
Mungkin bisa membantu orang lain yang menghadapi masalah yang sama. Anda dapat memuat file sebagai string dan kemudian dapat mengonversi string ke jsonobject untuk mengakses nilai.
import java.util.Scanner; import org.json.JSONObject; String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next(); JSONObject myJsonobject = new JSONObject(myJson);
sumber
Semoga contoh ini juga membantu
Saya telah melakukan pengkodean java dengan cara yang sama untuk contoh array json di bawah ini sebagai berikut:
berikut adalah format data json: disimpan sebagai "EMPJSONDATA.json"
[{"EMPNO": 275172, "EMP_NAME": "Rehan", "DOB": "29-02-1992", "DOJ": "10-06-2013", "ROLE": "JAVA DEVELOPER"},
{"EMPNO": 275173, "EMP_NAME": "GK", "DOB": "10-02-1992", "DOJ": "11-07-2013", "ROLE": "WINDOWS ADMINISTRATOR"},
{"EMPNO": 275174, "EMP_NAME": "Abiram", "DOB": "10-04-1992", "DOJ": "12-08-2013", "ROLE": "PROJECT ANALYST"}
{"EMPNO": 275174, "EMP_NAME": "Mohamed Mushi", "DOB": "10-04-1992", "DOJ": "12-08-2013", "ROLE": "PROJECT ANALYST"}]
public class Jsonminiproject { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json")); for (Object o : a) { JSONObject employee = (JSONObject) o; Long no = (Long) employee.get("EMPNO"); System.out.println("Employee Number : " + no); String st = (String) employee.get("EMP_NAME"); System.out.println("Employee Name : " + st); String dob = (String) employee.get("DOB"); System.out.println("Employee DOB : " + dob); String doj = (String) employee.get("DOJ"); System.out.println("Employee DOJ : " + doj); String role = (String) employee.get("ROLE"); System.out.println("Employee Role : " + role); System.out.println("\n"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
sumber
package com.json; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadJSONFile { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json")); JSONArray array = (JSONArray) obj; JSONObject jsonObject = (JSONObject) array.get(0); String name = (String) jsonObject.get("name"); System.out.println(name); String city = (String) jsonObject.get("city"); System.out.println(city); String job = (String) jsonObject.get("job"); System.out.println(job); // loop array JSONArray cars = (JSONArray) jsonObject.get("cars"); Iterator<String> iterator = cars.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
sumber
Contoh Json
{ "per_page": 3, "total": 12, "data": [{ "last_name": "Bluth", "id": 1, "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg", "first_name": "George" }, { "last_name": "Weaver", "id": 2, //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg", "first_name": "Janet" }, { "last_name": "Wong", "id": 3, //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg", "first_name": "Emma" } ], "page": 1, "total_pages": 4 }
Pernyataan If Pertama akan mengonversi data tunggal dari tubuh Kedua pernyataan if akan membedakan objek JsonArray
public static String getvalueJpath(JSONObject responseJson, String Jpath ) { Object obj = responseJson; for(String s : Jpath.split("/")) if (s.isEmpty()) if(!(s.contains("[") || s.contains("]"))) obj = ((JSONObject) obj).get(s); else if(s.contains("[") || s.contains("]")) obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", ""))); return obj.toString(); } }
sumber
Solusi menggunakan perpustakaan Jackson. Mengurutkan masalah ini dengan memverifikasi json di JSONLint.com dan kemudian menggunakan Jackson. Di bawah ini adalah kode yang sama.
Main Class:- String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n" + " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n" + " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n" + " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n" + " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]"; ObjectMapper mapper = new ObjectMapper(); MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class); for (MyPojo itr : jsonObj) { System.out.println("Val of getName is: " + itr.getName()); System.out.println("Val of getCity is: " + itr.getCity()); System.out.println("Val of getJob is: " + itr.getJob()); System.out.println("Val of getCars is: " + itr.getCars() + "\n"); } POJO: public class MyPojo { private List<String> cars = new ArrayList<String>(); private String name; private String job; private String city; public List<String> getCars() { return cars; } public void setCars(List<String> cars) { this.cars = cars; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } RESULT:- Val of getName is: John Val of getCity is: Berlin Val of getJob is: Teacher Val of getCars is: [FIAT, Toyata] Val of getName is: Mark Val of getCity is: Oslo Val of getJob is: Doctor Val of getCars is: [VW, Toyata]
sumber
file json Anda terlihat seperti ini
import java.io.*; import java.util.*; import org.json.simple.*; import org.json.simple.parser.*; public class JSONReadFromTheFileTest { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json")); JSONObject jsonObject = (JSONObject)obj; String name = (String)jsonObject.get("Name"); String course = (String)jsonObject.get("Course"); JSONArray subjects = (JSONArray)jsonObject.get("Subjects"); System.out.println("Name: " + name); System.out.println("Course: " + course); System.out.println("Subjects:"); Iterator iterator = subjects.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch(Exception e) { e.printStackTrace(); } } }
hasilnya adalah
mengambilnya dari sini
sumber
Anda dapat menggunakan readAllBytes.
return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);
sumber