简体   繁体   中英

Read JSON array in Java

I'm trying to read JSON file in Java (I'm starting with JSON).

The JSON file:

[
  {
    "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.

Thanks!

Use gson library to read and write 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

You are testing whether the iterator has a next element with 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. Therefore i.hasNext() will return true forever.

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.

You can use gson library

You can use Maven or jar file: 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. If you want to read and write json then you can use org.json library.

Use org.json library to parse it and create 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

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 :-

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

You can see complete example here, How to parse json in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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