[英]Read JSON array in Java
我正在嘗試用Java讀取JSON文件(我從JSON開始)。
JSON文件:
[
{
"idProducto":1,
"Nombre":"Coca Cola",
"Precio":0.9,
"Cantidad":19
},
{
"idProducto":2,
"Nombre":"Coca Cola Zero",
"Precio":0.6,
"Cantidad":19
},
[....]
]
我嘗試了以下方法:
ArrayList<Dispensador> Productos = new ArrayList<Dispensador>();
FileReader reader = new FileReader(new File("productos.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
Long idProducto = (Long) object.get("idProducto");
JSONArray nombres = object.getJSONArray("idProducto");
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
String nombre = (String) object.get("Nombre");
Double precio = (Double) object.get("Precio");
BigDecimal precioB = new BigDecimal(precio);
Long cantidad = (Long) object.get("Cantidad");
int cantidadB = toIntExact(cantidad);
System.out.println(nombre);
Productos.add(new Dispensador(nombre, precioB, cantidadB));
}
但進入循環。 我也嘗試了for循環,但沒有運氣。
謝謝!
使用gson庫來讀寫json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
下載http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
您正在測試迭代器是否具有i.hasNext()
的下一個元素。 但是你不會通過i.next()
消耗(或檢索)下一個元素,這通常是循環塊的第一個語句。 因此i.hasNext()
將永遠返回true。
編輯:您可能希望將object
設置為i.next()
因為在您的代碼片段中它始終保留在循環之前指定的0元素。
你可以使用gson庫
您可以使用Maven或jar文件: http : //mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
@Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
有許多開源庫,用於解析json到對象或只是讀取和寫入json值。 如果你想讀寫json那么你可以使用org.json庫。
使用org.json庫來解析它並創建JsonObject: -
JSONObject jsonObj = new JSONObject(<jsonStr>);
現在,使用此對象來獲取您的值: -
String id = jsonObj.getString("pageInfo");
你可以在這里看到完整的例子: -
如果你想將你的json解析為特定的POJO ,然后使用該pojo獲取值,那么使用jackson-databind庫,這將解析你的json到POJO類: -
ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);
你可以在這里看到完整的例子, 如何在java中解析json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.