android JSON data parsing

There are two main formats for downloading data on the Internet: XML and JSON, but these two data formats have their own format characters. Parsing the data is to extract the data we need from the two formats and remove the format characters. This article documents two common JSON parsing methods:

XML data parsing method: http://blog.csdn.net/q296264785/article/details/53897107

JSONObject analysis of JSON data analysis:

vate void withJSONObject(String jsonData) {
        try {
            //创建JSONArray实例
            JSONArray jsonArray = new JSONArray(jsonData);
            //遍历数组
            for (int i = 0; i < jsonArray.length(); i++) {
                //获取取出元素
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //取出内容
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d("MainActivity", "id is " + id);
                Log.d("MainActivity", "name is " + name);
                Log.d("MainActivity", "version is " + version);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

GSON analysis of JSON data analysis:
GSON analysis needs to add dependent libraries:

compile 'com.google.code.gson:gson:2.7'

First create a class that contains the parsed object node as a field and provides a get set method

public class App {
    private String id;
    private String name;
    private String version;

    public String getId() {// ALT + Insert 添加get set 方法
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

Pass in the required data

    private void withJSONGSON(String JSONData){
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(JSONData,new TypeToken<List<App>>(){}.getType());
        for(App app : appList){//遍历List 打印数据
            Log.d("MainActivity", "id is " + app.getId());
            Log.d("MainActivity", "name is " + app.getName());
            Log.d("MainActivity", "version is " + app.getVersion());
        }
    }
Published 34 original articles · Like 10 · Visits 30,000+

Guess you like

Origin blog.csdn.net/q296264785/article/details/53909442