bil*_*llz 80 java parsing json json-simple
我想JSON用java使用json简单库来读取这个文件.
我的JSON文件看起来像这样:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Run Code Online (Sandbox Code Playgroud)
这是我为阅读此文件而编写的java代码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到以下异常:
线程"main"中的异常java.lang.ClassCastException:org.json.simple.JSONArray无法强制转换为javaapplication1.JavaApplication1.main中的org.json.simple.JSONObject(JavaApplication1.java:24)
有人能告诉我我做错了什么吗?整个文件是一个数组,文件的整个数组中有对象和另一个数组(汽车).但我不知道如何将整个数组解析成java数组.我希望有人可以帮助我使用我在代码中遗漏的代码行.
谢谢
Gre*_*pff 75
整个文件是一个数组,文件的整个数组中都有对象和其他数组(例如汽车).
如你所说,JSON blob的最外层是一个数组.因此,您的解析器将返回一个JSONArray.然后你可以JSONObject从数组中得到s ...
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) person.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
Run Code Online (Sandbox Code Playgroud)
有关参考,请参阅json简单解码示例页面上的"示例1" .
Mad*_*ady 35
您可以使用jackson库并只使用这3行将您的json文件转换为Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
Run Code Online (Sandbox Code Playgroud)
添加Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
使用相关字段创建DTO类并读取JSON文件:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
Run Code Online (Sandbox Code Playgroud)
小智 7
从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;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用 Gson.
GSON是一个Java库,可用于将Java对象转换为其JSON表示形式.它还可用于将JSON字符串转换为等效的Java对象.
看看这个转换JSON到Java
使用google-simple库。
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
请在下面找到示例代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
将JSONObject用于简单的JSON之类{"id":"1","name":"ankur"},将JSONArray用于JSON的数组之类[{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}]。
可能对面临相同问题的其他人有所帮助。您可以将文件作为字符串加载,然后可以将字符串转换为 jsonobject 以访问值。
import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
Run Code Online (Sandbox Code Playgroud)
小智 5
Gson可以在这里使用:
public Object getObjectFromJsonFile(String jsonData, Class classObject) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(jsonData);
return gson.fromJson(object, classObject);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
494362 次 |
| 最近记录: |