`
pengfeifei26
  • 浏览: 241253 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

使用自带JSONObject解析JSON数据

 
阅读更多

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//获取解析的串,如下json串
public static String getJsonString(String urlPath) throws Exception {  
		StringBuffer sb = new StringBuffer();  
		try {
			
				URL url = new URL(urlPath);  
		        HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
		        connection.setConnectTimeout(50000);
		        connection.connect();  
		        InputStream inputStream = connection.getInputStream();  
		        //对应的字符编码转换  
		        Reader reader = new InputStreamReader(inputStream, "UTF-8");  
		        BufferedReader bufferedReader = new BufferedReader(reader);  
		        String str = null;  
		        while ((str = bufferedReader.readLine()) != null) {  
		            sb.append(str);  
		        }  
		        reader.close();  
		        connection.disconnect();  
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("连接超时。。。");
			return "timeout";
		}
       
        return sb.toString();  
    }  



json字串 :

{"response":"ok","result":{"userList":[{"name":"9S7B_music_user","id":162,"type":2,"date":1375780379000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":21,"gold":11},{"name":"fred26","id":129,"type":2,"date":1375781355000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":3,"ctCount":1,"myCount":1,"cgCount":7,"gold":3},{"name":"2VPL_music_user","id":170,"type":2,"date":1376032147000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":6,"gold":1},{"name":"T8D8_music_user","id":167,"type":2,"date":1375844980000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":6,"gold":15},{"name":"VFWR_music_user","id":159,"type":2,"date":1375777245000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":5,"gold":5},{"name":"dadaf","id":171,"type":2,"date":1376034139000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":4,"gold":2},{"name":"WGOL_music_user","id":166,"type":2,"date":1375843886000,"pwd":"e10adc3949ba59abbe56e057f20f883e","cyCount":1,"ctCount":1,"myCount":1,"cgCount":4,"gold":2}}]}}

相关方法

/**
	 * 将上述json串转成对象列表
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static  List jsonListToObjectList(String jsonStr)  throws Exception {
		List<User> userList = new ArrayList<User>();
			JSONObject jsonObject = new JSONObject(jsonStr);  
	        String response = jsonObject.getString("response");  

	        String json  = jsonObject.getString("result");

	        JSONObject jsonObject2 = new JSONObject(json); 
	        
    	  if(jsonStr.indexOf("userList") > -1){
          	String uList = jsonObject2.getString("userList");
          	if(null != uList){
          		// JSONObject jsonObject4 = new JSONObject(uList); 
          		JSONArray arry = jsonObject2.getJSONArray("userList"); 
          		for(int i=0;i<arry.length();i++){
                    JSONObject jsonObject5=(JSONObject)arry.get(i);

                    String name=jsonObject5.getString("name");
                    String cgCount=jsonObject5.getString("cgCount");
                    User user = new User();
                    user.setName(name);
                    user.setCgCount(Integer.parseInt(cgCount));
                    userList.add(user);
                }
          	}
    	  }
		return userList;
	}



public static Map jsonToObj(String jsonStr) throws Exception {  
        JSONObject jsonObject = new JSONObject(jsonStr);  
        String response = jsonObject.getString("response");  
        System.out.println("====================>response" +  response);
        String json  = jsonObject.getString("result");
        System.out.println("json=============>" + json);
        JSONObject jsonObject2 = new JSONObject(json); 
        
        String status = jsonObject2.getString("status");
        System.out.println("stauts------------>" +status);
        String name = "";
        String uid = "";
        String gold = "";
        if(jsonStr.indexOf("user") > -1){
        	String userJson = jsonObject2.getString("user");
        	if(null !=userJson){
           	 JSONObject jsonObject3 = new JSONObject(userJson); 
           	 	name = jsonObject3.getString("name");
           	 	uid = jsonObject3.getString("id");
           	 	gold = jsonObject3.getString("gold");
                System.out.println("name===>" + name);
           }
        }
        
        HashMap map = new HashMap();
        
        map.put("response", response);
        map.put("status", status);
        map.put("userName", name);
        map.put("uid", uid);
        map.put("gold", gold);
        return map;
        
        
//        JSONArray  result=jsonObject.getJSONArray("result");
//        
//        JSONArray data=result.getJSONArray(0);
        
        
      
//        int length = result.length();  
//        for (int i = 0; i < length; i++) {  
//            jsonObject = result.getJSONObject(1);  
//            String childName = jsonObject.getString("Name");  
//        }  
    }  
	
	
	
	public static Map jsonQuestionToObj(String jsonStr) throws Exception {  
        JSONObject jsonObject = new JSONObject(jsonStr);  
        String response = jsonObject.getString("response");  

        String json  = jsonObject.getString("result");

        JSONObject jsonObject2 = new JSONObject(json); 
        String answer = null;
        String gold = null;
        String uid = "";
        String qid = "";
        String cgCount = "";
        String name = "";
        String tips = "";
        String uqid = "";
        String isQuestion = jsonObject2.getString("isQuestion");
        if(isQuestion.equalsIgnoreCase("true")){
        	System.out.println("true------------------------->>>" + isQuestion);
        	  if(jsonStr.indexOf("question") > -1){
              	String questionJson = jsonObject2.getString("question");
              	if(null != questionJson){
              		 JSONObject jsonObject4 = new JSONObject(questionJson); 
              		 answer = jsonObject4.getString("answer");
              		 tips = jsonObject4.getString("tips");
              		 qid = jsonObject4.getString("id");
              		 System.out.println("answer----------------------->" + answer);
              	}
              }
        }
      
   
        if(jsonStr.indexOf("user") > -1){
        	String userJson = jsonObject2.getString("user");
        	if(null !=userJson){
           	 JSONObject jsonObject3 = new JSONObject(userJson);
           	 		uid = jsonObject3.getString("id");
                 name = jsonObject3.getString("name");
                gold = jsonObject3.getString("gold");
                cgCount = jsonObject3.getString("cgCount");
                System.out.println("name===>" + name);
                
           }
        }
        
        if(jsonStr.indexOf("userQuestion") > -1){
        	String userQuestionJson = jsonObject2.getString("userQuestion");
        	if(null !=userQuestionJson){
           	 JSONObject jsonObject3 = new JSONObject(userQuestionJson);
           	 		uqid = jsonObject3.getString("qid");
                 
                System.out.println("name===>" + uqid);
                
           }
        }
        
        
        
        
        HashMap map = new HashMap();
        
        map.put("isQuestion", isQuestion);
        map.put("answer", answer);
        map.put("qid", qid);
        map.put("tips", tips);
        
        map.put("response", response);
        map.put("uid", uid);
        map.put("name", name);
        map.put("cgCount", cgCount);
        map.put("gold", gold);
        
        map.put("uqid", uqid);
        
        return map;
	}


分享到:
评论

相关推荐

    android中JSON数据解析

    Android SDK自带了`org.json`库,它提供了一些基本的类如`JSONObject`和`JSONArray`,用于解析JSON数据。例如,当我们收到一个JSON对象时,可以使用`new JSONObject(jsonString)`构造一个`JSONObject`实例,然后...

    安卓中解析json数据.docx

    例如,可以使用`JSONObject`解析JSON对象,`JSONArray`解析JSON数组,通过`get()`和`opt()`方法获取键对应的值,`toString()`方法将解析后的数据转换回JSON字符串。 ```java String jsonString = "{\"name\":\...

    Android解析json数据

    1. `org.json`库:Android SDK自带的JSON解析库,提供了`JSONObject`和`JSONArray`类,可以方便地解析JSON字符串并从中获取数据。 2. `com.google.code.gson`: Google提供的Gson库,可以将Java对象直接转换为JSON...

    Android解析json数据示例代码(三种方式)

    本篇文章主要介绍了Android平台上解析JSON数据的三种方式,分别是Android自带解析、Gson解析和FastJson解析。 一、Android自带解析 在Android平台上,自带的JSON解析方式是使用JSONArray和JSONObject这两个类来...

    JSON数据的简单解析

    2. **org.json**:Android SDK自带的库,提供了JSONObject和JSONArray类来解析JSON: ```java JSONObject jsonObject = new JSONObject(jsonString); String name = jsonObject.getString("name"); JSONArray ...

    Android JSON数据的封装及解析

    1. **JSON对象解析**:使用`JSONObject`类解析JSON对象。 ```java JSONObject jsonObject = new JSONObject(jsonString); String name = jsonObject.getString("name"); ``` 2. **JSON数组解析**:使用`...

    android解析json数据)第一集JsonProject.zip

    - `JSONObject`:用于解析JSON对象,通过`get()`方法获取键对应的值。 - `JSONArray`:用于解析JSON数组,通过`get(int index)`获取指定索引的值。 4. Gson库使用:Google推出的Gson库可以直接将Java对象转换为...

    解析网络json数据demo

    1. **使用内置的`org.json`库**:这是Android SDK自带的一个简单库,提供了`JSONObject`和`JSONArray`类来解析JSON。例如: ```java JSONObject jsonObject = new JSONObject(jsonString); String value1 = ...

    android之json和gson数据解析最完整的代码例子(包括各种样式的json数据)

    在Android中,我们通常使用`org.json`库或`com.google.gson`库来解析JSON数据。 1. `org.json`库:这是Android SDK自带的一个轻量级库,主要用于解析简单的JSON数据。 - JSONObject:表示一个JSON对象,可以通过`...

    下载data数据之后使用系统自带的JSON解析

    下面我们将详细介绍如何在iOS中解析JSON数据。 首先,我们需要了解JSON的基本结构。JSON数据主要由对象(Object)和数组(Array)组成。对象以大括号 `{}` 包裹,键值对以冒号 `:` 分隔,各个键值对之间用逗号 `,` ...

    Android 安卓 json解析

    或解析JSON数组: ```java JSONArray jsonArray = new JSONArray(jsonData); for (int i = 0; i (); i++) { JSONObject obj = jsonArray.getJSONObject(i); // 解析对象属性 } ``` ### 3. 在线JSON解析 在线JSON...

    Android解析JSON数据

    在Android中,我们可以使用多种方法解析JSON数据: 1. **使用Gson库**:Gson是Google提供的一个Java库,能将Java对象转换为JSON字符串,反之亦然。在Android中,先引入Gson库,然后创建Java对象对应JSON结构,通过`...

    老罗Android视频开发教程 android解析Json数据代码

    在Android中,解析JSON数据通常有三种方式:使用Gson库、使用Android内置的JSONObject和JSONArray类,以及使用Fastjson库。 1. **Gson库**:由Google提供的Gson库可以将Java对象直接转换为JSON字符串,反之亦然。这...

    android JSON解析放入ListView

    - 解析JSON:使用上述的JSON库解析JSON字符串,转换为Java对象。 - 创建适配器:自定义一个继承自BaseAdapter的类,用于将Java对象绑定到ListView的各个Item。 - 设置ListView:将适配器设置到ListView上,通过...

    Android数据解析json

    在Android开发中,我们可以利用Java自带的`org.json`包来解析JSON数据。`org.json`包含两个主要类:`JSONObject`和`JSONArray`,分别用于表示JSON对象和数组。 **示例代码**: ```java try { String jsonString =...

    Android中gson、jsonobject解析JSON的方法详解

    本文将详细介绍如何在Android中使用Gson库和JSONObject来解析JSON数据。 ### 1. JSON对象和数组 JSON对象以大括号`{}`包裹,每个键值对以逗号分隔,键必须是字符串,值可以是任意JSON支持的数据类型。例如: ```...

    Android 解析json_dome.zip

    - `org.json`:这是Android SDK自带的库,提供了JSONObject和JSONArray类,可以方便地解析JSON对象和数组。 - `com.google.code.gson`: Google提供的Gson库,它能将Java对象转换为JSON字符串,反之亦然,功能更加...

    json解析所用到的所有包

    通过遍历解析事件,可以有效地构建和解析JSON数据。 6. **Fastjson**:阿里巴巴的Fastjson是一个高性能的JSON库,它提供了快速的序列化和反序列化功能,适用于Android开发。其API设计简洁,易于上手。 7. **使用...

    android demo,json数据格式的案例的应用

    2. org.json库:这是Android SDK自带的一个轻量级库,提供了JSONObject和JSONArray类来处理JSON数据。你可以使用`new JSONObject(jsonString)`来创建一个JSONObject,通过`get()`和`opt()`方法获取键对应的值,`put...

    Android应用源码之Android 解析json_dome.zip

    2. 使用`JSONObject`解析JSON对象,例如: ```java String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; JSONObject jsonObject = new JSONObject(jsonString); ``` 3. 使用`...

Global site tag (gtag.js) - Google Analytics