java - 在 servlet 中创建 json 对象

标签 java android json servlets

我想将检索到的数据从服务器发送到我的 Android 客户端...我使用了一个 json 对象来做到这一点。这是我的 servlet 代码。

import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

    public class AvailabilityResponse extends HttpServlet {

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType("application/json");
    PrintWriter out=response.getWriter();

        String br_id;
        br_id=request.getParameter("branchname");

    try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root");  
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select atmbrno, atmbrname  from location_stat where act_brname='"+br_id+"'");
            while(rs.next()){

        String s = rs.getString("atmbrno");
        String t = rs.getString("atmbrname");

        JSONObject arrayObj = new JSONObject();

        arrayObj.put("atmbrno",s);
        arrayObj.put("atmbrname",t);


        out.print(arrayObj);
        }
        rs.close ();
        st.close ();
           }
    catch(Exception e){
            out.print(e);
    }


}

这是我的android端代码..

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;

public class CheckAvailability extends Activity{

Button but1,but2;
EditText brName;
TextView txt1;
String text;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.availability);

    brName =(EditText)findViewById(R.id.editText1);
    but1 = (Button)findViewById(R.id.button5); 
    but2 = (Button)findViewById(R.id.button6);
    txt1 = (TextView)findViewById(R.id.textView3);



    but1.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){

            String result = null;
            InputStream is = null;
            StringBuilder sb=null;

           ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

           postParameters.add(new BasicNameValuePair("branchname", brName.getText().toString()));

        //http post
                  try{
                      HttpClient httpclient = new DefaultHttpClient();
                      HttpPost httppost = new HttpPost("http://10.0.2.2:8080/hello/AvailabilityResponse");
                      httppost.setEntity(new UrlEncodedFormEntity(postParameters));
                      HttpResponse response = httpclient.execute(httppost);
                      HttpEntity entity = response.getEntity();
                      is = entity.getContent();
                  }catch(Exception e){
                      Log.e("log_tag", "Error in http connection"+e.toString());
                  }

        //convert response to string
                  try{
                       BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                       sb = new StringBuilder();
                       sb.append(reader.readLine() + "\n");
                       String line="0";

                             while ((line = reader.readLine()) != null) {
                                 sb.append(line + "\n");
                             }
                             is.close();
                             result=sb.toString();

                  }catch(Exception e){
                        Log.e("log_tag", "Error converting result "+e.toString());
                         }

              //paring data
                        String atm_id;
                        String atm_name;

                        try{
                        JSONArray jArray = new JSONArray(result);
                        JSONObject json_data=null;

                        for(int i=0;i<jArray.length();i++){
                                json_data = jArray.getJSONObject(i);
                                atm_id=json_data.getString("atmbrno");
                                atm_name=json_data.getString("atmbrname");

                              //txt1.setText(atm_name);
                        }

                        }catch(JSONException e1){
                            Toast.makeText(getBaseContext(), "No DATA Found", Toast.LENGTH_LONG).show();

                        }catch (ParseException e1){
                            e1.printStackTrace();
                        }





        }
});

}

但是当我运行它时,它总是给我“未找到数据”异常...有人可以帮助我吗???

最佳答案

您的 servlet 仅返回 N 个 JSON 对象。但是你对 JSON 数组的响应可能是错误的在你的 servlet 中尝试这段代码

try{
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root");  
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select atmbrno, atmbrname  from location_stat where act_brname='"+br_id+"'");
            int i=0;
            JSONArray jArray = new JSONArray();
            while(rs.next()){

        String s = rs.getString("atmbrno");
        String t = rs.getString("atmbrname");

        JSONObject arrayObj = new JSONObject();

        arrayObj.put("atmbrno",s);
        arrayObj.put("atmbrname",t);

        jArray.add(i,arrayObj);
        i++;
        }
        rs.close ();
        st.close ();
        out.print(jArray);
    }

关于java - 在 servlet 中创建 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12364036/

相关文章:

android - Paypal future 付款协议(protocol)页面未在 android 中显示指向商户隐私政策和用户协议(protocol)的链接

android - 从图库中按缩放尺寸显示图像

json - 如何使用 Azure CLI 命令为 Azure Datafactory 创建 SQL 链接服务?

Java 泛型语法和调用接口(interface)类型(例如 List)上的方法

java - Grails 域类从哪里获取它们的查询方法?

java - 尝试在空对象引用上调用虚拟方法 'android.view.View android.view.View.findViewById(int)'

php - Ajax 。根据Element ID通过$.ajax()函数加载json数据

android - 如何在 dart/flutter 中提取 JSON 子数据

java - 运行时的 MapActivity ClassDefNotFoundException

java - 动态加载spring xml配置