使用GSON解析json数据feed



我有一个简单的JSON提要,它返回图像路径和一组坐标。"坐标"可以有无限的一组坐标。在我下面的例子中,它只有3个集合。

{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}

我如何使用GSON来解析这个?如何为此构建类呢?

谢谢

处理起来会很困难因为这不是有效的JSON

http://jsonlint.com/

如果它是有效的JSON,如…

{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}

我相信GSON可以将coords解析为<String, ArrayList<Integer>>map,但我需要尝试它以确保

添加gson-1.7.1.jar文件并编写此类以从url获取所需的JSONObjectJSONArray

public class GetJson {
    public JSONArray readJsonArray(String url) {
        String read = null;
        JSONArray mJsonArray = null;
        try {
            HttpClient http = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            HttpResponse response = http.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String str = null;
            while ((str = br.readLine()) != null) {
                builder.append(str);
            }
            is.close();
            read = builder.toString();
            mJsonArray = new JSONArray(read);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mJsonArray;
    }
    public JSONObject readJsonObject(String url) {
        String read = null;
        JSONObject mJsonObject = null;
        try {
            HttpClient http = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            HttpResponse response = http.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String str = null;
            while ((str = br.readLine()) != null) {
                builder.append(str);
            }
            is.close();
            read = builder.toString();
            mJsonObject = new JSONObject(read);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mJsonObject;
    }
}

享受……

然后解析JSON,参见这些教程,

教程1

教程2

教程3

最新更新