The author has 2 posts.
Font size: Small - 100% (Default)▼  Content converter: No conversion▼
 
Clicks Replies
1440 1
Android獲取JSON字符串並判斷是否為空字符串(適用於PHP中從XML轉換的JSON對象)
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 1 Posted at: 5/1/15 10:45
XML空節點:<string />  會被php的json_encode轉換為string:{}
XML帶文本節點的標籤:<string>something</string> 會被php的json_encode轉換為string:"something"
所以在讀取時需要在java中判斷

public static String getJSONString(JSONObject obj, String keyName) {
        try {
            obj.getJSONObject(keyName);
            // If succeeded, it is KEYNAME:{} and should actually be an empty string
            return "";
        } catch (JSONException e) {
            // If failed, it is a nonempty string (KEYNAME:"XXX")
            try {
                String keyString = obj.getString(keyName);
                return keyString;
            } catch (JSONException e1) {
                // If failed again, it is of other data types.
                return "";
            }
        }
    }
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 2 Posted at: 5/1/15 10:47
使用案例(把該函數放到App靜態類中)
try {
            JSONObject result = new JSONObject(network.result);
            JSONArray bars = result.getJSONArray("bar");
            barList.clear();
            barIDs.clear();
            for (int i = 0; i < bars.length(); i++) {
                JSONObject bar = bars.getJSONObject(i);
                String details = String.format(App.res.getString(R.string.bar_details), bar.getString("creator"));
                
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("PostTitle", bar.getString("name"));
                map.put("PostContent", App.getJSONString(bar,"shortDescription"));
                map.put("PostDetails", details);
                
                barList.add(map);
                barIDs.add(bar.getInt("ID"));
            }
            adapter.notifyDataSetChanged();
            ((ListView)findViewById(R.id.listView1)).setSelection(0);
            displayed = true;
        } catch (JSONException e1) {
            App.alert("JSONException");
            e1.printStackTrace();
        }
Reply the post
Content:
User: You are currently anonymous.
Captcha:
Unclear? Try another one.
(Shortcut key: Ctrl+Enter)
Post Information
Clicks: 1440 Replies: 1
Author: 巨大八爪鱼
Last reply: 巨大八爪鱼
Last reply time: 5/1/15 10:47
Bar Good Posts
Announcements