luochunlin855520
luochunlin855520
采纳率25%
2017-09-04 07:38 阅读 10.4k

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

5

执行到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 蚂蚁冲锋队 2017-09-04 08: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();
            }
        }
    }
    
    点赞 1 评论 复制链接分享
  • j550341130 叽哩叽哩鸡 2017-09-04 07:45

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

    点赞 评论 复制链接分享
  • qq_24249533 LXGiiii 2017-09-04 07:59

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

    点赞 评论 复制链接分享

相关推荐