2 luochunlin855520 luochunlin855520 于 2017.09.04 15:38 提问

String字符串转换成json格式并打印json数据。

执行到150行的时候,不抱错,也没有执行后面的语句,我想请教大神String转json格式然后存储到本地数据库,有什么办法。
package sql_conn;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.swing.*;
import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.sql.Types;
import java.io.BufferedReader;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class java_sql extends JFrame{

JTextArea jtf1,jtf2;
JButton yellowbutton,bluebutton,redbutton,okbutton;
private static String test_url="jdbc:jtds:sqlserver://192.168.5.14:1433;DatabaseName=EUCP5";
private static String test_user = "admin123";  
private static String test_pwd = "abcd_12345"; 
private static Connection con = null;  

public static void main(String[] args) {  
    // TODO Auto-generated method stub  
    EventQueue.invokeLater(new Runnable() {  

        @Override  
        public void run() {  
            // TODO Auto-generated method stub  
            java_sql frame=new java_sql();
            frame.setVisible(true);  

        }  
    });  
}  

public java_sql(){  

    this.setTitle("EUCP_数据库连接调试工具");  
    this.setSize(600,600);  
    okbutton=new JButton("提交");
    okbutton.setVisible(true);     
    /*按钮添加button1Handler监听*/
    okbutton.addActionListener(new Button1Handler());  
    //add buttons to panel  
    buttonPanel=new JPanel();    
    buttonPanel.add(okbutton);

    this.add(buttonPanel);   

}

private class Button1Handler implements ActionListener{
    public void actionPerformed(ActionEvent e){

        try {
            java_sql sms=new java_sql();
            //jtf2.setText(okbutton.getActionCommand());
            //JOptionPane.showMessageDialog(null, e.toString(), "alter", JOptionPane.ERROR_MESSAGE);
            sms.send_middle("177612309","验证码是48907");

        } catch (Exception ex) {

            //JOptionPane.showMessageDialog(null, ex.toString(), "alter", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

private JPanel buttonPanel;  


public static int send_middle(String url, String param) throws MalformedURLException,
        UnsupportedEncodingException {
    String inputLine = "";
    int value = -2;
    String con;
    DataOutputStream out = null;


    //InputStream in = null;
    String strUrl="http://eucpwx.mb345.com:443/AppApi/User/GetUserList?";
    String strparam = "UserID=SU0126&GetType=1&NowID=&GetNum=100&Other=&SearchUserName=";

    try {
        System.out.println("start");
        inputLine = sendPost(strUrl, strparam);
        //value = new Integer(inputLine).intValue();
        System.out.println(inputLine);
        String str=String.valueOf(inputLine);

        //JSONObject st = JSONObject.fromObject(str);

        JSONObject jsonObject = new JSONObject().fromObject(str.toString());
        System.out.println("可以");
        Object data=jsonObject.get("UserID");
        jsonObject = new JSONObject().fromObject(data.toString());
        data=jsonObject.get("data");
        jsonObject = new JSONObject().fromObject(data.toString());
        data=jsonObject.get("value");
        int value_k = Integer.parseInt(data.toString());

        /*
        Statement stmt = null;  
        String strSQL = "";        
        String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String dbURL="jdbc:slserver://192.168.5.14:1433;DatabaseName=EnterpriseSMS_Play";
        String userName="admin";
        String userPwd="abcd";
        Class.forName(driverName);
        Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd);  
        String sql = ""; //注意java对SQL Server发送的SQL语句中表名需要用[]包围
        System.out.println("SQL 开始"); 
        for (int i = 0; i < jsonArr.size(); i++) {  
            userid[i] = jsonArr.getJSONObject(i).getString("userid");  
            username[i] = jsonArr.getJSONObject(i).getString("username");  
            mobile[i] = jsonArr.getJSONObject(i).getString("mobile");  
            Avatar[i] = jsonArr.getJSONObject(i).getString("Avatar");  

            sql = "INSERT into user_bak (userid, username, mobile, Avatar) values('"+userid[i]+"','" +username[i]+"','"+mobile[i]+ "','"+Avatar[i]+"');";    
            System.out.println(sql.toString()); 
            PreparedStatement statement = null; 
             statement = dbConn.prepareStatement(sql); 
             ResultSet rs = statement.executeQuery();
             rs.close();
             statement.close();
             dbConn.close();

            File f = new File("log.txt");      
            if (!f.exists())   
            {       
                f.createNewFile();      
            }      
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"utf-8");      
            BufferedWriter writer=new BufferedWriter(write);          
            writer.write(content);      
            writer.close();   
        }*/

    } catch (Exception e) {
        //System.out.println(e.toString());
        value = -2;
    }
    //System.out.println(String.format("返回值:%d", value));
    return value;
}

/**
 * 向指定 URL 发送POST方法的请求
 * 
 * @param url
 *            发送请求的 URL
 * @param param
 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 * @return 所代表远程资源的响应结果
 */
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) {
            //System.out.println(line);
            //String send_line =URLEncoder.encode(line.toString(), "utf-8");
            //JOptionPane.showMessageDialog(null, line.toString(), "alter", JOptionPane.ERROR_MESSAGE);
            //System.out.println(line.toString());
            result += line;
            //System.out.println(result.toString());
        }
    } 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;
}

}

图片说明

3个回答

baidu_26611019
baidu_26611019   2017.09.04 16:41
已采纳
 给你一个自己写的例子,实现bean转成JSONPObject,并输出JSONPObject的内容
public class JsonTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        person per=new person("xx",20);
        JSONPObject jobj=new JSONPObject("p", per);
        System.out.println(jobj.getValue().toString());
    }

    static class person{
        private String name;
        private int age;
        public person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return "name = "+getName()+", age ="+getAge();
        }
    }
}
baidu_26611019
baidu_26611019 我导了org.json.JSONObject 是完全没问题的String str = "{\"result\":\"success\",\"message\":\"成功!\"}"; JSONObject json=new JSONObject(str.toString()); System.out.println(json.get("result")+" "+ json.get("message")); 输出success 成功! 我怀疑是你的收到的json格式不对,由json.get(key)得不到值
2 个月之前 回复
baidu_26611019
baidu_26611019 你把你打印出来的字符串发过来我试一下
2 个月之前 回复
luochunlin855520
luochunlin855520 嗯,打印出来是string 类型的 json格式数据。json更换用了org.json包,还是报错,已经快被搞晕了
2 个月之前 回复
baidu_26611019
baidu_26611019 先排除问题,1、接口接收到的数据格式问题,将接受到的String打印出来,然后再作为虚构数据测试。2、json包问题,替换其他的包试试
2 个月之前 回复
luochunlin855520
luochunlin855520 回复蚂蚁冲锋队: 我试过虚构json字符串,输出是成功的。接口取的返回值就是不认 JSONObject js = JSONObject.parseObject(String);我用的是fastjson.jar包。
2 个月之前 回复
baidu_26611019
baidu_26611019 虚构json字符串,String str = "{\"result\":\"success\",\"message\":\"成功!\"}"; 再JSONPObject jobj=new JSONPObject("p", str);输出 {"result":"success","message":"成功!"}
2 个月之前 回复
baidu_26611019
baidu_26611019 JSONPObject jobj=new JSONPObject("p", "xxxx"); System.out.println(jobj.getValue().toString()); 可以输出xxxx的。如果你无法打印出字符串的内容可采取以下措施:1、转化前先打印一下字符串,确保字符串为有效值。2、替换你的json包,我的是jackson-annotations-2.5.0.jar jackson-core-2.5.0.jar jackson-databind-2.5.0.jar 这三个包
2 个月之前 回复
luochunlin855520
luochunlin855520 现在我接口有json格式返回值,不用构造,在String转 json过程中出了问题,也不报错
3 个月之前 回复
j550341130
j550341130   2017.09.04 15:45

推荐使用 FastJson 或者 Gson, 可以直接解析为 JavaBean, 一分钟就学会

qq_24249533
qq_24249533   2017.09.04 15:59

fastjson:JSONObject js = JSONObject.parseObject(String);
试一试

luochunlin855520
luochunlin855520 引用了fastjson,JSONObject js = JSONObject.parseObject(String); 报parseObject未定义
3 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片