简体   繁体   English

用Java读取JSON数组

[英]Read JSON array in Java

I'm trying to read JSON file in Java (I'm starting with JSON). 我正在尝试用Java读取JSON文件(我从JSON开始)。

The JSON file: JSON文件:

[
  {
    "idProducto":1,
    "Nombre":"Coca Cola",
    "Precio":0.9,
    "Cantidad":19
  },
  {
    "idProducto":2,
    "Nombre":"Coca Cola Zero",
    "Precio":0.6,
    "Cantidad":19
  },
[....]
]

I tried the following: 我尝试了以下方法:

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

But enters into loop. 但进入循环。 Also I tried with a for loop, but no luck. 我也尝试了for循环,但没有运气。

Thanks! 谢谢!

Use gson library to read and write json: 使用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();
        }

download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip 下载http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip

You are testing whether the iterator has a next element with i.hasNext() . 您正在测试迭代器是否具有i.hasNext()的下一个元素。 But you don't consume (or retrieve) this next element by i.next() which is typically in the first statement of the looped block. 但是你不会通过i.next()消耗(或检索)下一个元素,这通常是循环块的第一个语句。 Therefore i.hasNext() will return true forever. 因此i.hasNext()将永远返回true。

EDIT: You probably want to set object to i.next() because in your code snippet it always remains at the 0's element you assigned before the loop. 编辑:您可能希望将object设置为i.next()因为在您的代码片段中它始终保留在循环之前指定的0元素。

You can use gson library 你可以使用gson

You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/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 + "]";
    }

}

There are many open source libraries, present to parse json to object or just to read and write json values. 有许多开源库,用于解析json到对象或只是读取和写入json值。 If you want to read and write json then you can use org.json library. 如果你想读写json那么你可以使用org.json库。

Use org.json library to parse it and create JsonObject :- 使用org.json库来解析它并创建JsonObject: -

JSONObject jsonObj = new JSONObject(<jsonStr>);

Now, use this object to get your values :- 现在,使用此对象来获取您的值: -

String id = jsonObj.getString("pageInfo");

You can see complete example here :- 你可以在这里看到完整的例子: -

How to parse Json in java 如何在java中解析Json

If you want to parse your json to particular POJO and then use that pojo to get values, then use jackson-databind library, this will parse your json to POJO class :- 如果你想将你的json解析为特定的POJO ,然后使用该pojo获取值,那么使用jackson-databind库,这将解析你的json到POJO类: -

ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);

You can see complete example here, How to parse json in java 你可以在这里看到完整的例子, 如何在java中解析json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM