在BlackBerry上将JSONArray转换为Vector

时间:2013-12-23 15:43:21

标签: json blackberry java-me

我能够将字节流转换为其JSON表示。这是一个JSONArray。我希望它转换为Vector中的bb_test个对象。我该怎么做?

我使用了json的这个例子 http://codeoncloud.blogspot.com/2013/05/blackberry-java-json-tutorial.html

我从服务器获取数据如下:

[
    {
        "settingName": "New",
        "onclick": "CreateNewDoc()"
    },
    {
        "settingName": "Open",
        "settingValue": "OpenDoc()"
    },
    {
        "settingName": "Close",
        "settingValue": "CloseDoc()"
    }
]

所以我创建了一个这样的类

package mypackage;

public class bb_test {
    String settingName;
    /**
     * 
     */
    String settingValue;
    public String getSettingName() {
        return settingName;
    }
    public void setSettingName(String settingName) {
        this.settingName = settingName;
    }
    public String getSettingValue() {
        return settingValue;
    }
    public void setSettingValue(String settingValue) {
        this.settingValue = settingValue;
    }

}

2 个答案:

答案 0 :(得分:0)

首先,将这些参数存储在两个名为settingNameArraysettingValueArray的字符串数组中,您将接收此JSON数据。像这样的东西

假设您在以下数组中收到了整个JSON,那么

JSONArray arr=new JSONArray(jsonData);
int size=arr.length();
String[] settingNameArray=new String[size];
String[] settingValueArray=new String[size];
JSONObject[] obj=new JSONObject[size];
for(int i=0;i<size;i++)
{
    settingNameArray[i]=arr.getJSONObject(i).getString("settingName");
    settingValueArray[i]=arr.getJSONObject(i).getString("settingValue");
}

bb_test.setSettingValue(settingValueArray);
bb_test.setSettingName(settingNameArray);

之后,更改bb_test的类结构以保存这些值。它看起来像这样

public class bb_test {
    String settingName[];
    String settingValue[];
    public bb_test ()
    {   
    }
    public String[] getSettingName() {
        return settingName;
    }
    public void setSettingName(String[] settingName) {
        this.settingName = settingName;
    }
    public String[] getSettingValue() {
        return settingValue;
    }
    public void setSettingValue(String[] settingValue) {
        this.settingValue = settingValue;
    }
}

答案 1 :(得分:0)

你的bb_test类很好,不需要改变它,除了命名约定。您可以从这样的数据中获取数组:

Vector bb_testVector = new Vector();
JSONArray jsonArray = new JSONArray(jsonData);
int size = jsonArray.length();

    for(int i=0;i<size;i++)
    {
        JSONObject tempJSON = jsonArray.getJSONObject(i);

        String settingName = tempJSON.getString("settingName");
        String settingValue = tempJSON.getString("settingValue");

        bb_test newBBTest = new bb_test();
        newBBTest.setSettingName(settingName);
        newBBTest.setSettingValue(settingValue);

        bb_testVector.addElement(newBBTest);

        //clean memory
        tempJSON = null;
        newBBTest = null;
        settingName = null;
        settingValue = null;
    }