简体   繁体   中英

Java reading JSON with multiple objects

The json looks like:

{
  "id": "SMAAZGD20R",
  "data": [
    {
      "blukiiId": "CC78AB5E73C8",
      "macAddress": "CC78AB5E73C8",
      "type": "SENSOR_BEACON",
      "battery": 97,
      "advInterval": 1000,
      "firmware": "003.007",
      "rssi": [
        {
          "rssi": -96,
          "timestamp": 1594642177138
        }
      ],
      "beaconSensorData": {
        "environment": [
          {
            "airPressure": 994.4,
            "light": 5,
            "humidity": 26,
            "temperature": 28.4,
            "timestamp": 1594642177138
          }
        ]
      }
    }
  ]
}

The code looks like:

public class getJSON
{
   
   public static void main(String[] args) throws Exception{
       JSONParser parser = new JSONParser();
       
       try{
           Object obj = parser.parse(new FileReader("C:\\test.json"));
           JSONObject jsonObj = (JSONObject)obj;
           JSONArray jsonArr = (JSONArray)jsonObj.get("data");
           
           Iterator itr = jsonArr.iterator();
           
           while(itr.hasNext()){
               System.out.println(itr.next());
            }
           
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
}

Output:

{"macAddress":"CC78AB5E73C8","rssi":[{"rssi":-96,"timestamp":1594642177138}],"advInterval":1000,"blukiiId":"CC78AB5E73C8","type":"SENSOR_BEACON","battery":97,"firmware":"003.007","beaconSensorData":{"environment":[{"light":5,"airPressure":994.4,"temperature":28.4,"humidity":26,"timestamp":1594642177138}]}}

I get an Array with the object "data", but the array includes only one value with all objects from "data". How can i address the array "environment" and get the values tempreature, light,...

Have you should try to use a framework like jackson Who will let unmarshall your json to real java object of your choice for example:

public class Data
{
   private String blukiiId;
   private String macAddress;
   private String type;
   ...
   private List<RSSI> rssi;
   private BeaconSensorData beaconSensorData;
}

With Rssi,BeaconSensorData another class like that etc... Now your code will get Converted as below

public class getJSON
{
   
   public static void main(String[] args) throws Exception{
       ObjectMapper mapper = new ObjectMapper();
       // Set any extra configs like ignore fields etc here

       try{
            Data data = mapper.convertValue(Files.readAllBytes(Paths.get("test.json"), Data.class);

            //Now you can access the value as below
            data.getBeaconSensorData().getEnvironment().getTemperature();
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
}


If you can only use org.json.simple.parser.JSONParser, please refer to the following java code by recursion.

import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class getJSON
{
    private static void visitElement(Object obj, Map<Object, Object> map) throws Exception {
        if(obj instanceof JSONArray) {
            JSONArray jsonArr = (JSONArray)obj;
            Iterator<?> itr = jsonArr.iterator();
            while(itr.hasNext())
                visitElement(itr.next(), map);
        }
        else if(obj instanceof JSONObject) {
            JSONObject jsonObj = (JSONObject)obj;
            Iterator<?> itr = jsonObj.keySet().iterator();
            while(itr.hasNext()) {
                Object key = itr.next();
                Object value = jsonObj.get(key);
                map.put(key, value);
                visitElement(value, map);                 
            }
        }
    }
   
   public static void main(String[] args) throws Exception{
       JSONParser parser = new JSONParser();
       
       try{
           Object obj = parser.parse(new FileReader("C:/test.json"));
           Map<Object, Object> map = new HashMap<>();
           visitElement(obj, map);
           for(Object key : map.keySet())
               System.out.println(key + ": " + map.get(key));
           
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
}

Look at my code below.

[

{
    "title": "Dywizjon 303",
    "year": 2019,
    "type": "Dokumentalny",
    "director": "Zbigniew Zbigniew",
    "actors": ["Maria Joao","Jose Raposo"]
    
},

{
    "title": "Szeregowiec Ryan",
    "year": 2006,
    "type": "Historyczny",
    "director": "Stanislaw Stanislaw",
    "actors": ["Rosa Canto","Amalia Reis","Maria Garcia"]
},

{
    "title": "Duzy",
    "year": 1988,
    "type": "Dramat",
    "director": "Penny Marshall",
    "actors": ["Rosa Canto"]
},

{
    "title": "Syberiada Polska",
    "year": 2013,
    "type": "Wojenny",
    "director": "Janusz Zaorski",
    "actors": ["Harvey Glazer"]
}

]

This is my Entity named Movie

package objectMapper.app;

import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName="Class")
public class Movie {
    
    @JacksonXmlProperty(localName="title")
    private String title;
    
    @JacksonXmlProperty(localName="year")
    private int year;
    
    @JacksonXmlProperty(localName="type")
    private String type;
    
    @JacksonXmlProperty(localName="director")
    private String director;
    
    @JacksonXmlProperty(localName="actors")
    private String[] actors;
    
    public Movie()
    {
        
    }

    

    public Movie(String title, int year, String type, String director, String[] actors) {
        this.title = title;
        this.year = year;
        this.type = type;
        this.director = director;
        this.actors = actors;
    }



    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    

    public String[] getActors() {
        return actors;
    }



    public void setActors(String[] actors) {
        this.actors = actors;
    }



    @Override
    public String toString() {
        return "Movie [title=" + title + ", year=" + year + ", type=" + type + ", director=" + director + ", actors="
                + Arrays.toString(actors) + "]";
    }



    
    
    

}

Function to read movies.json

public Movie[] readJSONFile() throws JsonParseException, JsonMappingException, IOException
    {
        
        ObjectMapper mapper= new ObjectMapper();
        Movie[] jsonObj=mapper.readValue(new File("movies.json"),Movie[].class);
        return jsonObj;
    }

Lets do something with our POJO class

List<String> titles=new ArrayList(); 
        for(Movie itr: tempMovies)
        {
            titles.add(itr.getTitle().toLowerCase());
        }
        if(titles.contains(tempTitle.toLowerCase()))
        {
        for(Movie itr2 : tempMovies)
        {
            
            if(tempTitle.toLowerCase().equals(itr2.getTitle().toLowerCase()))
            {
                System.out.println("Title: "+itr2.getTitle());
                System.out.println("Year: "+itr2.getYear());
                System.out.println("Type: "+itr2.getType());
                System.out.println("Director: "+itr2.getDirector());
                String[] tempActorsStrings=itr2.getActors();
                int size=tempActorsStrings.length;
                for(int i=0;i<size;i++)
                {
                    System.out.println("Actor: "+tempActorsStrings[i]);
                }
                status=false;
            }
            
        }
        }
        else
        {
            System.out.println("Movie title does not exist!");
        }

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