简体   繁体   中英

Php list object to java arraylist object

I am trying to fetch data from database using php and send it to java using json. Using java, I wanted to retrieve json values from an arraylist. That arrayList will contain Fruit Object. But in my code, I get values inside arraylist and that arraylist contains LinkedHashMap and not the fruit object. How do I change the php code so that in java side I could get values like ArrayList fruitList = new ArrayList();

<?php
    require("phpfunc.fns");
    include('Fruit.php');
    sqlconnect();

    $data = array();
    $fruit = new Fruit();
    $sql="select * from fruit";         
    $result=mysql_query( $sql);
    $count = 0;

    while( $r=mysql_fetch_array($result) ){
        //echo $r['lati'].",". $r['longi'] ;
        $fruit->setFruitId($r['fruitId']);
        $fruit->setAvailable($r['available']);

        $data[$count] = $fruit;
        $count++;
    }
    echo json_encode($data);

?>

  //java code
public void decodeUsingGSON(String json){
        Gson gson = new Gson();
        ArrayList fruitList = gson.fromJson(json, ArrayList.class);

        for(int i=0; i<fruitList.size(); i++){
            Fruit fruit = (Fruit) fruitList.get(i);
            System.out.println(fruit.getAvailable());
        }
    }

You should read up on the Gson documentation . It describes how to handle generic data types and collections . The following should work for you, assuming properly formed JSON:

final Type collectionType = new TypeToken<Collection<Fruit>>(){}.getType();
final Collection<Fruit> fruits = gson.fromJson(json, collectionType);

for(final Fruit fruit; fruits) {
    System.out.println(fruit.getAvailable());
}

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