English 中文(简体)
• 如何将JSON数据归入安的[复制]
原标题:How to parse JSON data in Android [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Sending and Parsing JSON in Android

我是从服务器上收集的JSON数据,我已经通过代码输入JSON数据。 但是,我不理解如何加以区别。

Here is my code for server i am fetching data from mysql database and then sending to android device

   import java.io.*;
   import java.util.*;
   import javax.sql.*;
   import javax.servlet.*;
   import javax.servlet.http.*;
   import java.sql.Connection;
   import java.sql.DriverManager;
   import java.sql.ResultSet;
   import java.sql.SQLException;
   import java.sql.Statement;
   import net.sf.json.JSONArray;

   public class DBConnection extends HttpServlet {
          public void doGet(HttpServletRequest request,HttpServletResponse     response)throws IOException, ServletException{

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

    // connecting to database
    Connection con = null;    
    Statement stmt = null;
    ResultSet rs = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con =DriverManager.getConnection("jdbc:mysql://localhost:3306/emarnew", "root","12345");
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM allpatientdetails WHERE patientname= Mr Hans Tan ");


    // displaying records
        while(rs.next()){
    JSONArray arrayObj=new JSONArray();
        String name="patientname"+rs.getObject(1).toString();
    arrayObj.add(name);

        arrayObj.add(rs.getObject(2).toString());
        arrayObj.add(rs.getObject(3).toString());
        arrayObj.add(rs.getObject(4).toString());
        arrayObj.add(rs.getObject(5).toString());
        arrayObj.add(rs.getObject(6).toString());
        arrayObj.add(rs.getObject(7).toString());
        arrayObj.add(rs.getObject(8).toString());
        String nik =arrayObj.toString();

           // fetch the parameters from client..

            final String user = request.getParameter("UID");
             // out.print(user);

             if("patients".equals(user))
               out.print(nik);
            else 
               out.println("fail");

         // out.print(nik);
           //   out.print("			");
             //   out.print("<br>");

}
    } catch (SQLException e) {
        throw new ServletException("Servlet Could not display records.", e);
      } catch (ClassNotFoundException e) {
          throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
                if(stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if(con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {}
        }

        out.close();
    }

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{
    this.doGet(request, response);
}


}

And here is my android code import java.util.ArrayList; import java.util.List;

       import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.NameValuePair;
       import org.apache.http.client.HttpClient;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.HttpGet;
       import org.apache.http.client.methods.HttpPost;
             import org.apache.http.impl.client.DefaultHttpClient;
         import org.apache.http.message.BasicNameValuePair;
         import org.apache.http.protocol.HTTP;
        import org.apache.http.util.EntityUtils;

      import android.app.Activity;
       import android.os.Bundle;
       import android.util.Log;
       import android.widget.TextView;

     public class ClientActivity extends Activity 
      {
TextView tv;
public  StringBuffer buffer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv= (TextView)findViewById(R.id.tv);

    try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://10.0.2.2:8080/nik/DBConnection?UID=patients";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("UID", "patients"));
            //params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                //Log.i("RESPONSE",EntityUtils.toString(resEntity));
                buffer = new StringBuffer("");
                buffer.append(EntityUtils.toString(resEntity));

            }

           String String1= buffer.toString();
           Log.i("string-----",String1);
           tv.append(String1);



    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://10.0.2.2:8080/nik/DBConnection?UID=patients";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));

                }
} catch (Exception e) {
    e.printStackTrace();
}
}
}

结果是,一是接见汉斯·坦先生”、“S2234567”、“75945422”、“20-11-1971”、“Chronic Hepatatis C”、“Copegus 400毫克”、“8”、“Ward3A-1,301”等,而一是需要加以整顿,请提供任何帮助。 预 收

最佳回答

您使用JSONObject和/或JSONArray等类别,将JSON数据和roid。

基本用途如下:

JSONObject jsonObject = new JSONObject(myJsonDataString);

以及

JSONArray jsonArray = new JSONArray(myJsonDataString);

You can find more info on the usage at the Android Developers Page, specifically here 以及 here.

<>Restrong Be 谨慎: 格式数据:“[关键:价值}]” (如果谈论[] s)就必须与JSONArray或你拿到一名JSONException的话说,你的数据是一目标。

问题回答

暂无回答




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

How to get instance from string in C#?

Is it possible to get the property of a class from string and then set a value? Example: string s = "label1.text"; string value = "new value"; label1.text = value; <--and some code that makes ...

XML DOM parsing br tag

I need to parse a xml string to obtain the xml DOM, the problem I m facing is with the self closing html tag like <br /> giving me the error of Tag mismatch expected </br>. I m aware this ...

Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

Locating specific string and capturing data following it

I built a site a long time ago and now I want to place the data into a database without copying and pasting the 400+ pages that it has grown to so that I can make the site database driven. My site ...

热门标签