我正在尝试用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循环,但没有运气。
谢谢!
答案 0 :(得分:1)
使用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
答案 1 :(得分:1)
您正在测试迭代器是否具有i.hasNext()
的下一个元素。但是你不会消耗(或检索)i.next()
这个下一个元素,这通常是循环块的第一个语句。因此i.hasNext()
将永远返回true。
编辑:您可能希望将object
设置为i.next()
,因为在您的代码段中,它始终保留在您在循环之前指定的0元素。
答案 2 :(得分:1)
您可以使用 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 + "]";
}
}
答案 3 :(得分:0)
有许多开源库,用于解析json到object或只是读取和写入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);
您可以在此处查看完整示例,How to parse json in java