Parsing JSON Array using GSON

后端 未结 2 940
甜味超标
甜味超标 2020-12-06 15:07

I have a basic JSON with all data contained in an array. One would think that it would be simple to retreive a value out of the array, but after multiple hours of trying eve

2条回答
  •  -上瘾入骨i
    2020-12-06 15:38

    i have also faced json array parsing using gson here is my code solved it

    this is my reader class functions

    JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(myFile)));
    	System.out.println( reader);
    		 Gson gson = new Gson();
    		    JsonParser parser = new JsonParser();
    			   JsonArray jArray = parser.parse(reader).getAsJsonArray();
    			    ArrayList lcs = new ArrayList();
     for(JsonElement obj : jArray )
    	    {
    	    	JsonOperations cse = gson.fromJson( obj , JsonOperations.class);
    			    	
    		        lcs.add(cse);
    	  }
    	    for ( JsonOperations tUser : lcs)
    		  		{
    			  		  System.out.println(tUser);
    			  		}

    my json operation class is

    public class JsonOperations {
    	String match_id, pool_name, team1_name, team1_image, team2_name,
    			team2_image, match_date, match_country, match_venue, predicted;
    
    	public JsonOperations() {
    		
    	}
    
    	public JsonOperations(String match_id, String pool_name, String team1_name,
    			String team1_image, String team2_name, String team2_image,
    			String match_date, String match_country, String match_venue,
    			String predicted) {
    
    		this.match_id = match_id;
    		this.pool_name = pool_name;
    		this.team1_name = team1_name;
    		this.team1_image = team1_image;
    		this.team2_name = team2_name;
    		this.team2_image = team2_image;
    		this.match_date = match_date;
    		this.match_country = match_country;
    		this.match_venue = match_venue;
    		this.predicted = predicted;
    
    	}
    
    	public void set_team1(String team1_name) {
    
    		this.team1_name = team1_name;
    	}
    
    	public void set_team2(String team2_name) {
    
    		this.team2_name = team2_name;
    	}
    
    	public String get_team1() {
    
    		return team1_name;
    	}
    
    	public String get_team2() {
    
    		return team2_name;
    	}
    
    	@Override
    	public String toString() {
    		// TODO Auto-generated method stub
    		return this.get_team1() + this.get_team2();
    	}
    
    }

提交回复
热议问题