java吧 关注:1,263,368贴子:12,762,459
  • 10回复贴,共1

关于java处理json的问题

只看楼主收藏回复

[{"id":"1","name":"n1"},{"id":"2","name":"n2"}]
求大神帮忙,上面这个是我用java通过URLConnection从php获取到的json数据,得到的这个数据是string类型的,我要怎么才能把里面的数据按照key->values的方式读取出来,网上找了很多资料表示都不太符合我这个情况,大神们帮帮小弟么


IP属地:重庆1楼2017-05-09 01:44回复
    package httpPost2;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import org.json.simple.JSONValue;
    public class Test {
    public static String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
    URL realUrl = new URL(url);
    // 打开和URL之间的连接
    URLConnection conn = realUrl.openConnection();
    // 设置通用的请求属性
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    // 发送POST请求必须设置如下两行
    conn.setDoOutput(true);
    conn.setDoInput(true);
    // 获取URLConnection对象对应的输出流
    out = new PrintWriter(conn.getOutputStream());
    // 发送请求参数
    out.print(param);
    // flush输出流的缓冲
    out.flush();
    // 定义BufferedReader输入流来读取URL的响应
    in = new BufferedReader(
    new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    result += line;
    }
    } catch (Exception e) {
    System.out.println("发送 POST 请求出现异常!" + e);
    e.printStackTrace();
    }
    // 使用finally块来关闭输出流、输入流
    finally {
    try {
    if (out != null) {
    out.close();
    }
    if (in != null) {
    in.close();
    }
    } catch (IOException ex) {
    ex.printStackTrace();
    }
    }
    return result;
    }
    public static void main(String[] args) {
    Test test = new Test();
    String string = test.sendPost("http://localhost/book/class_bro/get_book_info.php", "type1=1");
    Object json = JSONValue.parse(string);
    //这里的object实际存储的就是一个json字符串
    System.out.println(json);
    }
    }


    IP属地:重庆2楼2017-05-09 01:45
    回复
      2025-06-09 02:53:32
      广告
      大神们还请帮帮忙,么么哒


      IP属地:重庆3楼2017-05-09 01:47
      回复
        java解析json我记得有个现成的包来着……叫org.json.lib来着?


        4楼2017-05-09 01:54
        收起回复
          没办法 就用 正则


          IP属地:江西5楼2017-05-09 01:57
          收起回复
            搞定了没


            IP属地:江西6楼2017-05-09 02:53
            收起回复