如何在我的对象中为getter提供数组值?

时间:2018-04-12 15:45:39

标签: java android arrays json

我的JSON Array具有此格式,我正在尝试toast user_review_ids值 - 63,59,62。我不断得到我认为值reference的值,而不是值本身 - 我进入toast'[Ljava.lang.String.;@41c19f...这样的东西。

根据我的阅读,我认为像copyOfclone()这样的方法可以做到这一点,但没有快乐。

我的JSON Array采用这种格式,在我的服务器上:

       [{"cat_name":"name1","user_review_ids":[63,59,62],
    "private_review_ids":[],"public_review_ids":["9999"],"user_personal_count":3,
"private_count":0,"public_count":1}]

当我尝试toast user_personal_countprivate_countpublic_count的任何值时,我都没有问题,只有数组。

以下是Category对象中的代码:

    String cat_name;
    String [] user_review_ids;
    String user_personal_count;
    String private_count;
    String public_count;

    public Category() {
    }

    public String getName() {
        //return the value of the JSON key named cat_name in php file
        return cat_name;
    }


    public String[] getUserReviewIds() {
        //return the value of the JSON key named user_personal_count in php file
       // return user_personal_count;
        return user_review_ids;
    }

    public String getUserPersonalCount() {
        //return the value of the JSON key named user_personal_count in php file
        return user_personal_count;
    }

    public String getPrivateCount() {
        //return the value of the JSON key named private_count in php file
        return private_count;
    }

    public String getPublicCount() {
        return public_count;
    }
}

和烘烤值的函数,在另一个类中:

@Override
public void onContactSelected(Category category) {
    Toast.makeText(getApplicationContext(), "Selected: " + category.getUserReviewIds(), Toast.LENGTH_LONG).show();
}

2 个答案:

答案 0 :(得分:1)

执行:

Arrays.toString(category.getUserReviewIds())
按照here解释,在你的Toast中

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));

所以你的方法应该是这样的:

@Override
public void onContactSelected(Category category) {
    Toast.makeText(getApplicationContext(), "Selected: " + Arrays.toString(category.getUserReviewIds()), Toast.LENGTH_LONG).show();
}

我不知道您的应用是什么,但Toasts绝对不是向用户展示内容的最佳方式。

否则,要回答您的问题,是的,您正在显示对数组的引用,而不是数组本身,这就是为什么您有@41c19f

答案 1 :(得分:1)

使用String.join(delimiter,stringArray);。在delimiter的地方,您可以使用逗号(,)或其他内容。

@Override
    public void onContactSelected(Category category) {
        Toast.makeText(getApplicationContext(), "Selected: " + String.join(",",category.getUserReviewIds()), Toast.LENGTH_LONG).show();
    }