GSON问题解析JSON数组

时间:2017-02-13 15:46:22

标签: json gson

这是我的问题。我得到一个stacktrace试图将这个json反序列化为一个字符串数组。这是我的json

$manager

这是我的代码

class User {

    private $dbHost     = "localhost:27017";
    private $dbName     = "Demo";
    private $userTbl    = 'google_users';


    function __construct(){
        //Connecting to MongoDB
        try {

            $this->manager = new MongoDB\Driver\Manager( 'mongodb://'. $this->dbHost ); 
        //  ^^^^^ make a class property
        }
        catch (MongoDB\Driver\Exception\Exception $e) {

            echo $e->getMessage(), "\n";
        }
    }


    function checkUser($userData = array()){
        if(!empty($userData)){
            //Check whether user data already exists in database

            $filter = ['oauth_uid' => $userData['oauth_uid'], 'oauth_provider' => $userData['oauth_provider']];
            $prevQuery = new MongoDB\Driver\Query($filter);
            $user_count=0;

            try {

                $cursor = $this->manager->executeQuery($this->dbName.'.'.$this->userTbl, $prevQuery);
                //        ^^^^^ reuse the class property

                // Iterate over all matched documents
                foreach ($cursor as $document) {
                    $user_count++; //will return 0 if user doesn't exist
                }

            } catch (MongoDB\Driver\Exception\Exception $e) {
                echo $e->getMessage(), "\n";
            }  
        }
    }
}

这是我的stacktrace

[{"productId":"primary_savings","productName":"Primary Savings - Required Membership Account","productAmount":"0","isForFunding":"true"}]

我在这里做错了什么?我见过其他stackoverflow问题,但似乎没有解决我的问题。

请协助

2 个答案:

答案 0 :(得分:2)

这里的问题是输入不是字符串数组:它是一个包含一个具有字符串值的对象的数组。您必须迭代地提取字符串或创建一个类来映射对象,例如:

class Product {
  String productName;
  String productId;
  String productAmount;
  String isForFunding;
}

然后

Product[] product = gson.fromJson(array1, Product[].class)

答案 1 :(得分:0)

使用以下类型:

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = gson.fromJson(array1, listType);

GSON API documentation