【问题标题】:Php list object to java arraylist objectphp列表对象到java arraylist对象
【发布时间】:2012-03-04 14:44:07
【问题描述】:

我正在尝试使用 php 从数据库中获取数据并使用 json 将其发送到 java。使用 java,我想从数组列表中检索 json 值。该 arrayList 将包含 Fruit 对象。但是在我的代码中,我在 arraylist 中获取值,并且该 arraylist 包含 LinkedHashMap 而不是水果对象。如何更改 php 代码,以便在 java 端我可以获得像 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());
        }
    }

【问题讨论】:

    标签: java php json


    【解决方案1】:

    您应该阅读Gson documentation。它描述了如何handle generic data types and collections。假设 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());
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 2018-08-07
      • 2021-03-28
      • 2013-06-11
      • 2013-03-31
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多