經常使用的幾種JSON方式

一、原生的json解析:

// 下載字符串
	public String loadUrlJson(String url) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "UTF-8");

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

// JSON解析
	public List<Map<String, Object>> parseJOSN(String json) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			JSONObject jsonObject = new JSONObject(json);
			JSONArray jsonarray = jsonObject.getJSONArray("items");
			for (int i = 0; i < jsonarray.length(); i++) {
				Map<String, Object> itemMap = new HashMap<String, Object>();
				JSONObject jsonItems = jsonarray.getJSONObject(i);
				itemMap.put("image", jsonItems.getString("image"));
				itemMap.put("content", jsonItems.getString("content"));
				itemMap.put("comments_count",
						jsonItems.getString("comments_count"));
				JSONObject loginObj = jsonItems.getJSONObject("user");
				if(loginObj!=null){
					itemMap.put("login", loginObj.getString("login"));		
				}else{
					itemMap.put("login", "");	
				}

				list.add(itemMap);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return list;
	}

二、原生JSON跟Gson的配合使用

	// GSON????JSON???
	public List<Feed> parseJSON(String json) {
		// ??????GSON????????JSON?????????????GSON?????????????????JSON????????????
		List<Feed> list = new ArrayList<Feed>();
		try {
			JSONObject jsonObject = new JSONObject(json);
			JSONArray jsonArray = jsonObject.getJSONObject("paramz")
					.getJSONArray("feeds");
			// ???feeds??????????????GSON????
			Gson gson = new Gson();
			TypeToken<List<Feed>> typeToken = new TypeToken<List<Feed>>() {
			};
			list = gson.fromJson(jsonArray.toString(), typeToken.getType());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	};

三、淘寶的FastJson跟原生的Json配合使用的解析

public void responseText(String txet) {
		try {
			JSONArray josnArray = new JSONObject(txet).getJSONArray("data");
			List<CbkData> list = JSON.parseArray(josnArray.toString(),
					CbkData.class);
			listCbk.clear();
			listCbk.addAll(list);
			adapter.notifyDataSetChanged();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
//使用實體類的源生解析,用Volley框架下載
 private void loadData(String urls) {
        final Gson gson = new Gson();
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest jsonRequest = new JsonObjectRequest(0, urls, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("MainActivity", "JSONObject" + response.toString());
                // Log.e("MainActivity","JSONObject2"+ gson.fromJson(response.toString(), HealthLore.class));
                List<HealthLore> loads = new ArrayList<>();
                try {
                    JSONArray jsonArray = response.getJSONArray("list");
                    int length = jsonArray.length();
                    for (int i = 0; i <length ; i++) {
                        HealthLore healthLore = new HealthLore();
                        int id = jsonArray.getJSONObject(i).getInt("id");
                        String title = jsonArray.getJSONObject(i).getString("title");
                        String description = jsonArray.getJSONObject(i).getString("description");
                        String message = jsonArray.getJSONObject(i).getString("message");
                        int count = jsonArray.getJSONObject(i).getInt("count");
                        String img = jsonArray.getJSONObject(i).getString("img");
                        String keywords = jsonArray.getJSONObject(i).getString("keywords");
                        String time = jsonArray.getJSONObject(i).getString("time");
                        int fcount = jsonArray.getJSONObject(i).getInt("fcount");
                        int rcount = jsonArray.getJSONObject(i).getInt("rcount");
                        int loreclass = jsonArray.getJSONObject(i).getInt("loreclass");
                        healthLore.setIn_id(id);
                        healthLore.setTitle(title);
                        healthLore.setDescription(description);
                        healthLore.setMessage(message);
                        healthLore.setCount(count);
                        healthLore.setImg(img);
                        healthLore.setKeywords(keywords);
                        healthLore.setTime(time);
                        healthLore.setFcount(fcount);
                        healthLore.setRcount(rcount);
                        healthLore.setLoreclass(loreclass);
                        loads.add(healthLore);
                    }

                    //配合GSON的解析
//                    JSONArray tngou = response.getJSONArray("list");
//                    TypeToken<List<HealthLore>> typeToken = new TypeToken<List<HealthLore>>() {
//                    };
//                    loads = gson.fromJson(tngou.toString(), typeToken.getType());
                    // healths.clear();
                    healths.addAll(loads);
                    Log.e("MainActivity", "healths" + healths.toString() + "healthssize" + healths.size());
                    Log.e("MainActivity", "healthssize" + healths.size());
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
相關文章
相關標籤/搜索