在Android中没有正确解析和分割JSON

时间:2013-06-28 03:50:54

标签: android json

我正在尝试使用未知数据解析JSON ArrayJSON就像这样来了

{
    "info": [
        {
            "1": "4",
            "Store #": " 0560",
            "How many microwave circuits did you run?": " 3",
            "How many new ovens did you deliver to the store?": " 1",
            "How many new racks did you deliver to the store?": " 5",
            "Voltage readings on Turbo Chef 1": " 64",
            "Voltage readings on Turbo Chef 2": " 54",
            ...
        }
    ],
    "success": 1
}

现在因为我不知道数据会在收到之前是什么,所以我不能使用像

这样的传统方法
for (int i = 0; i < info.length(); i++) {

    JSONObject c = info.getJSONObject(i);

    String store = c.getString("Store #");
}

所以我试图使用这种代码方法而且我不成功

try {
    // Checking for SUCCESS TAG
    int success = json.getInt(TAG_SUCCESS);

    if (success == 1) {
        info = json.getJSONArray(TAG_INFO);
        for (int i = 0; i < info.length(); i++) {
            if (info != null) {                 
                    clientList.add(info.get(i).toString());                 
            }
        }
        for (String s : clientList) {
            Log.v("CHECKING S", s);
            s.split(":");
            Log.v("CHECKING S SPLIT", s);
            values.add(s);
            Log.v("CHECKING VALUES 0", values.get(0));
            mQuestions.add(values.get(0));
            Log.v("CHECKING VALUES 1", values.get(1));
            mAnswers.add(values.get(1));                        
        }

    } 

然而,我的日志告诉我,不仅数据没有被分割并放入ArrayLists,因为我希望它保持在JSON形式。这是logcat

06-27 23:32:54.479: V/CHECKING S(32540): {"Were any of the steamers gas?":" yes","Voltage readings on Turbo Chef 4":" 34","Voltage readings on Turbo Chef 3":" 43","Voltage readings on Turbo Chef 2":" 54","Did you label all the outlets?":" yes","Voltage readings on Turbo Chef 1":" 64","How many new ovens did you deliver to the store?":" 1","If yes, did you cap the water lines?":" yes","Phone #":" (740) 389-1174","Has all new equipment been installed & have you confirmed it is all working properly?":" yes","How many new racks did you deliver to the store?":" 5","Are all oven circuits tied into electrical shut down for hood?":" yes","How many Back steamers did you remove?":" none","Date":" 6-24-13","Zip":" 43302","How many oven circuits did you run?":" 2","How many microwave circuits did you run?":" 3","If yes, did you cap the gas lines?":" yes","Did you remove the existing FRONT steamers?":" yes","Did you remove the existing BACK steamers?":" no","Voltage readings on microwave circuit 1":" 57","City":" Marion","Voltage readings on microwave circuit 3":" 92","If yes, how?  Shunt Tripp  or Contactor":" shunt tripp","Voltage readings on microwave circuit 2":" 87","How many front steamers did you remove?":" 2","1":"4","State":" OH","Store #":" 0560","How many existing steamers did you remove for disposal off-site?":" none","Address":" 1318 Mount Vernon Avenue","Tech Name":" Jon Doe"}
06-27 23:32:54.479: V/CHECKING S SPLIT(32540): {"Were any of the steamers gas?":" yes","Voltage readings on Turbo Chef 4":" 34","Voltage readings on Turbo Chef 3":" 43","Voltage readings on Turbo Chef 2":" 54","Did you label all the outlets?":" yes","Voltage readings on Turbo Chef 1":" 64","How many new ovens did you deliver to the store?":" 1","If yes, did you cap the water lines?":" yes","Phone #":" (740) 389-1174","Has all new equipment been installed & have you confirmed it is all working properly?":" yes","How many new racks did you deliver to the store?":" 5","Are all oven circuits tied into electrical shut down for hood?":" yes","How many Back steamers did you remove?":" none","Date":" 6-24-13","Zip":" 43302","How many oven circuits did you run?":" 2","How many microwave circuits did you run?":" 3","If yes, did you cap the gas lines?":" yes","Did you remove the existing FRONT steamers?":" yes","Did you remove the existing BACK steamers?":" no","Voltage readings on microwave circuit 1":" 57","City":" Marion","Voltage readings on microwave circuit 3":" 92","If yes, how?  Shunt Tripp  or Contactor":" shunt tripp","Voltage readings on microwave circuit 2":" 87","How many front steamers did you remove?":" 2","1":"4","State":" OH","Store #":" 0560","How many existing steamers did you remove for disposal off-site?":" none","Address":" 1318 Mount Vernon Avenue","Tech Name":" Jon Doe"}
06-27 23:32:54.479: V/CHECKING VALUES 0(32540): {"Were any of the steamers gas?":" yes","Voltage readings on Turbo Chef 4":" 34","Voltage readings on Turbo Chef 3":" 43","Voltage readings on Turbo Chef 2":" 54","Did you label all the outlets?":" yes","Voltage readings on Turbo Chef 1":" 64","How many new ovens did you deliver to the store?":" 1","If yes, did you cap the water lines?":" yes","Phone #":" (740) 389-1174","Has all new equipment been installed & have you confirmed it is all working properly?":" yes","How many new racks did you deliver to the store?":" 5","Are all oven circuits tied into electrical shut down for hood?":" yes","How many Back steamers did you remove?":" none","Date":" 6-24-13","Zip":" 43302","How many oven circuits did you run?":" 2","How many microwave circuits did you run?":" 3","If yes, did you cap the gas lines?":" yes","Did you remove the existing FRONT steamers?":" yes","Did you remove the existing BACK steamers?":" no","Voltage readings on microwave circuit 1":" 57","City":" Marion","Voltage readings on microwave circuit 3":" 92","If yes, how?  Shunt Tripp  or Contactor":" shunt tripp","Voltage readings on microwave circuit 2":" 87","How many front steamers did you remove?":" 2","1":"4","State":" OH","Store #":" 0560","How many existing steamers did you remove for disposal off-site?":" none","Address":" 1318 Mount Vernon Avenue","Tech Name":" Jon Doe"}
06-27 23:32:54.479: W/System.err(32540): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
06-27 23:32:54.479: W/System.err(32540):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
06-27 23:32:54.479: W/System.err(32540):    at java.util.ArrayList.get(ArrayList.java:304)
06-27 23:32:54.489: W/System.err(32540):    at com.facilitysolutionsinc.trackflex.Client$Load.doInBackground(Client.java:131)
06-27 23:32:54.489: W/System.err(32540):    at com.facilitysolutionsinc.trackflex.Client$Load.doInBackground(Client.java:1)
06-27 23:32:54.489: W/System.err(32540):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-27 23:32:54.489: W/System.err(32540):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-27 23:32:54.489: W/System.err(32540):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-27 23:32:54.489: W/System.err(32540):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-27 23:32:54.489: W/System.err(32540):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-27 23:32:54.489: W/System.err(32540):    at java.lang.Thread.run(Thread.java:856)

那么我做错了什么?如果您需要更多代码询问,我会发布。谢谢你的帮助

修改

根据我收到的答案,我对代码进行了修订。它现在看起来像这样

try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
info = json.getJSONArray(TAG_INFO);
    for (int i = 0; i < info.length(); i++) {
        if (info != null) {             
            clientList.add(info.get(i).toString());             
        }
    }
    for (String s : clientList) {
        Log.v("CHECKING S", s);
        String[] str_arr= s.split("[:,]");                                              
        Log.v("CHECKING VALUES 0", str_arr[0]);
        mQuestions.add(str_arr[0]);
        Log.v("CHECKING VALUES 1", str_arr[1]);
    }
    for (String content : mQuestions) {
        Log.v("QUESTIONS", content);
    }

}

然而,现在只在我JSON ArrayLists中存储06-28 00:19:10.679: V/CHECKING VALUES 0(1724): {"Were any of the steamers gas?" 06-28 00:19:10.679: V/CHECKING VALUES 1(1724): " yes" 06-28 00:19:10.679: V/QUESTIONS(1724): {"Were any of the steamers gas?" 的第一行,因为logcat显示

{{1}}

2 个答案:

答案 0 :(得分:4)

您好我已经为您做了这件事。我只是粘贴下面的完整代码。尝试使用这种json,它一定会对你有用。

我将该方法称为:

String data = "{'info': [{'1': '4','Store #': ' 0560','How many microwave circuits did you run?': ' 3','How many new ovens did you deliver to the store?': ' 1','How many new racks did you deliver to the store?': ' 5','Voltage readings on Turbo Chef 1': ' 64','Voltage readings on Turbo Chef 2': ' 54'}],'success': 1}";

    try {
        JSONObject jsonData = new JSONObject(data);
        populateFromResponse(jsonData);

        } catch (JSONException e) {
            System.out.println(" Exception occured" + e.getMessage());
             e.printStackTrace();
        }
    }

现在populateFromResponse()方法的实现如下:

private static final String TAG_SUCCESS = "success"; private static final String TAG_INFO = "info"; private ArrayList<JSONObject> clientList; private ArrayList<String> mQuestions; private ArrayList<String> mAnswers;

  public void populateFromResponse(JSONObject json) throws JSONException {

    // parse the response   if (json != null) {

        // Checking for SUCCESS TAG         int success = json.getInt(TAG_SUCCESS);         // checking for null        if (success == 1) {             JSONArray info = json.getJSONArray(TAG_INFO);           if (info != null) {
                for (int i = 0; i < info.length(); i++) {
                    // checking for null
                    if (info.get(i) != null
                            && info.get(i) instanceof JSONObject)
                        if (clientList == null) {
                            clientList = new ArrayList<JSONObject>();
                        }
                    clientList.add(info.getJSONObject(i));
                }           }

            for (JSONObject s : clientList) {
                Log.v("CHECKING S", s.toString());
                // Iterator containing all the keys
                Iterator<String> iterator = s.keys();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    String value = s.getString(key);

                    print("CHECKING VALUES 0: " + key);
                    // checking for null
                    if (mQuestions == null) {
                        mQuestions = new ArrayList<String>();
                    }
                    mQuestions.add(key);

                    print("CHECKING VALUES 1: " + value);
                    // checking for null
                    if (mAnswers == null) {
                        mAnswers = new ArrayList<String>();
                    }
                    mAnswers.add(value);
                }

                print("CHECKING S SPLIT: " + s);

            }       }   } else {        print("response is null");  }

}

private void print(String string) {     System.out.println("######-- " + string + " -----#########"); }

输出为:

01-04 19:38:20.332: I/System.out(7685):
 ######-- CHECKING S SPLIT: {"1":"4","Voltage readings on Turbo Chef 2":" 54","Voltage readings on Turbo Chef 1":" 64","How many microwave circuits did you run?":" 3","Store #":" 0560","How many new racks did you deliver to the store?":" 5","How many new ovens did you deliver to the store?":" 1"} -----#########


01-04 19:38:20.332: I/System.out(7685): ######-- CHECKING VALUES 0: {"1" -----#########
01-04 19:38:20.332: I/System.out(7685): ######-- CHECKING VALUES 1: "4","Voltage readings on Turbo Chef 2" -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: 1 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1: 4 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: Voltage readings on Turbo Chef 2 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  54 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: Voltage readings on Turbo Chef 1 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  64 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: How many microwave circuits did you run? -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  3 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: Store # -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  0560 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: How many new racks did you deliver to the store? -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  5 -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 0: How many new ovens did you deliver to the store? -----#########
01-04 19:52:32.362: I/System.out(7841): ######-- CHECKING VALUES 1:  1 -----#########


01-04 19:52:32.363: I/System.out(7841): ######-- CHECKING S SPLIT: {"1":"4","Voltage readings on Turbo Chef 2":" 54","Voltage readings on Turbo Chef 1":" 64","How many microwave circuits did you run?":" 3","Store #":" 0560","How many new racks did you deliver to the store?":" 5","How many new ovens did you deliver to the store?":" 1"} -----#########

现在享受代码并开心。 再见。

答案 1 :(得分:1)

您需要将s.split(":")结果分配给String Array:

for (String s : clientList) {
             Log.v("CHECKING S", s);
             String[] str_arr= s.split(":"); //<<<<<
             Log.v("CHECKING S SPLIT", str_arr);

             Log.v("CHECKING VALUES 0", str_arr[0]);
             mQuestions.add(str_arr[0]);
             Log.v("CHECKING VALUES 1", str_arr[1]);
             mAnswers.add(str_arr[1]);                        
        }