开发者

Using GSON to parse a json datafeed

i have a simple JSON feed which returns an im开发者_如何学Pythonage path, and a set of coordinations. The "coords" can have an unlimited set of coordinations. In my example below it only has 3 set.

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

How would i use GSON to parse this? How do I build the class for this?

Thanks


You're going to have a hard time with that because it's not valid JSON.

http://jsonlint.com/

If it were valid JSON such as ...

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

I believe GSON could parse coords to a map of <String, ArrayList<Integer>> but I'd need to try it to make sure.


Add the gson-1.7.1.jar file and write this class to get the required JSONObject or JSONArray from the url.

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;
    }
}

ENJOY...

Then to parse the JSON see the these tutorials,

Tutorial 1

Tutorial 2

Tutorial 3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜