java json处理

java 解析json数据例子:

json数据demo1 :

{"errCode":"0","data":{"validDrawNumToday":0}}

json数据demo2:

{"errCode":"0","data":{"validDrawNumToday":0,"drawQrcodeUrl":"http://h5.itv.cp21.ott.cibntv.net/lottery/draw/acceptqrcode.html?devId=test_x","prize":{"id":2,"name":"多啦a梦星座","picTv":"http://i1.img.cp21.ott.cibntv.net/lc04_iscms/201607/28/10/39/f8aebd254c4c4a51903f56ea5a6dd4ec.png","picMobile":"http://i3.img.cp21.ott.cibntv.net/lc06_iscms/201607/29/11/22/c100737ff9af47ba86bebbc07e8216d3.png"}}}java 的访问url解析json内容,保存指定的字段“prize”字段的值

package tvguess;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class changedevid {

    public static String getWebContent(String Url) {
        HttpGet httpGet = new HttpGet(Url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
       
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null)
            try {
                return EntityUtils.toString(entity, "UTF-8");
            } catch (ParseException | IOException e) {
                e.printStackTrace();
            }
        return null;
    }

    /**
     * json中可以不带字prize字段
     * @param strResult
     * @return
     */
    public static String parseJsonMulti(String strResult) {
        System.out.println("parse start....");
        String prize = "";

        try {
            JSONObject jobject = new JSONObject(strResult);
            JSONObject jdata = jobject.getJSONObject("data");
            System.out.println(jdata);

//循环查找出json属性值
            Iterator<?> objkey=jdata.keys();
            while (objkey.hasNext()){
                String aa2 = (String) objkey.next().toString();    
                String bb2 = jdata.getString(aa2);
                System.out.println(aa2+":"+bb2);
               
                if(aa2.equals("prize")){
                    System.out.println("------------");
                    String prizeresult = bb2;
                    System.out.println("prizerresult:"+ prizeresult);
                    fileprize("prize.txt", prizeresult);
                }else{
                    System.out.println("no prize");
                   
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return prize;
    }
   
    /**
     * json中必须带prize的字段
     * @param strResult
     * @return
     */
    public static String parseJsonMulti01(String strResult) {
        System.out.println("parse start....");
        String prize = "";

        try {

// 直接查找元素子元素
            JSONObject jobject = new JSONObject(strResult);
            JSONObject jdata = jobject.getJSONObject("data");
            JSONObject jprize = jdata.getJSONObject("prize");
            prize = jprize.getString("id") + "," + jprize.getString("name") + "/n";
            System.out.println(prize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return prize;
    }
   
    public static void fileprize(String fileName, String content) {
        RandomAccessFile randomFile = null;
        try {
            randomFile = new RandomAccessFile(fileName, "rw");
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        int x = (int) (Math.random() * 100000);
        //String strUrl = "http://h5.itv.cp21.ott.cibntv.net/api/lottery/draw.json?devId=test_" + x;
        String strUrl = "http://10.58.100.90/jsondatedemo.txt";
        System.out.println(strUrl);
        String strResult = getWebContent(strUrl);
        System.out.println(strResult);
        String prize = parseJsonMulti(strResult);
        //String prize = parseJsonMulti01(strResult);
        //fileprize("prize.txt", prize);
    }
}
--------------------------------------------------------------------------------------

json查找数组的代码

public String parseJsonMulti(String strResult) {
//    public void parseJsonMulti(String strResult,TextView etContent) {
        System.out.println("parse start....");
        String channelid = "";
        //List livelist = new ArrayList();
       
        try {
            //JSONArray jsonArray = new JSONArray(String.valueOf(msg.obj));
            JSONObject jsonObject = new JSONObject(strResult.toString());  
            JSONArray arrayJson = jsonObject .getJSONArray("data"); 
          //  etContent.setText("parse start...");
            String str = "urlconnect:";
           
            for (int i=0;i<arrayJson.length();i++)
                 
            {
                 JSONObject tempJson = arrayJson.optJSONObject(i);
               //JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
               str=str+"第"+i+"个,频道id:"+tempJson.getString("channelId")+"\n";
              
              
            //   etContent.setText(str);
              //   str2 = str2+"type:"+tempJson.getString("type")+"频道id:"+tempJson.getString("channelId")+"\n";
                // str2 = str2+tempJson.getString("type")+tempJson.getString("channelId");
               channelid=channelid+tempJson.getString("channelId")+",";
            //     livelist.add(i);
        //         etContent.setText(str2);
                 System.out.println(channelid);
                
                
                // Log.v("zms", str);
                
            }
            System.out.print(str);
           } catch (JSONException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
         //       etContent.setText("error");
           }
       
        return channelid;
       
    }  
   

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
处理嵌套json格式的数据。。。 public static void main(String[] args) { // 官方API http://www.json.org/java/ /* 购物车中信息 goods_cart={cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}}; * **/ try{ String s0 = "{cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}};"; String s= java.net.URLDecoder.decode(s0, "utf-8"); System.out.println(s); JSONObject o = new JSONObject(s); System.out.println(o.get("cart_1325036696007")); //根据属性,获取值 System.out.println(o.toString()); //得到字符串 System.out.println(o.names().get(2)); //获取对象中第三组属性名 System.out.println(o.names().length()); //获取对象中属性个数 //System.out.println(o.names().getJSONArray(1)); //获取对象中属性个数 //names(jsonObjectName) 私有方法 获取该对象的所有属性名,返回成JSONArray。 //JSONObject.getNames(jsonObjectName) 静态方法 获取对象的所有属性名,返回成数组。 System.out.println(JSONObject.getNames(o.getJSONObject("cart_1325036696007"))[1]); System.out.println(o.getJSONObject("cart_1325036696007").names().get(1)); System.out.println(o.length()); //共有几组对象 System.out.println(o.has("cart_1325036696007")); //有无该该值 /* 遍历json中的每一组元素*/ String name = null; JSONObject t_o = null; for(int i=0; i<o.length(); i++){ name = JSONObject.getNames(o)[i]; System.out.println("商品项ID:"+name); t_o = o.getJSONObject(name); for(int j=0; j< t_o.length(); j++){ name = JSONObject.getNames(t_o)[j]; System.out.print(name+":"+t_o.get(name)+" "); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值