字符串转换为一个JSON对象 [英] Convert string to a json object

查看:216
本文介绍了字符串转换为一个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从出现从一个servlet在我的服务器的响应字符串创建JSON对象。

 公共类JSONParser {静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;//构造
公共JSONParser(){}    公众的JSONObject getJSONFromUrl(URL字符串,字符串一){        ArrayList的<&的NameValuePair GT; postParameters =新的ArrayList<&的NameValuePair GT;();
        postParameters.add(新BasicNameValuePair(分支名称,一));        尝试{
            // defaultHttpClient
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HttpPost httppost =新HttpPost(URL);
            httppost.setEntity(新UrlEn codedFormEntity(postParameters));            HTT presponse HTT presponse = httpClient.execute(httppost);
            HttpEntity httpEntity = HTT presponse.getEntity();
            是= httpEntity.getContent();        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }
        返回jObj;
}}

这是我的servlet。

 公共类AvailabilityResponse延伸的HttpServlet {@覆盖
    保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)
    抛出了ServletException,IOException异常{    PrintWriter的OUT = response.getWriter();        串br_id;
        br_id =的request.getParameter(分支名称);    尝试{
                的Class.forName(com.mysql.jdbc.Driver)的newInstance()。
                连接CON =的DriverManager.getConnection(JDBC的:mysql://本地主机:8888 / atmlivedetails,根,根);
        声明ST = con.createStatement();
        结果集RS = st.executeQuery('+ br_id +从哪里location_stat = act_brname选择atmbrno,atmbrname');
        INT I = 0;
        JSONArray jArray =新JSONArray();
        而(rs.next()){    字符串s = rs.getString(atmbrno);
    串T = rs.getString(atmbrname);    JSONObject的arrayObj =新的JSONObject();    arrayObj.put(atmbrno,S);
    arrayObj.put(atmbrname,T);    jArray.add(ⅰ,arrayObj);
    我++;
    }
    rs.close();
    st.close();
    的out.print(jArray);
}    赶上(例外五){
            的out.print(E);
    }
}}

但是当我运行这个它说错误

 分析数据org.json.JSONException:值[{atmbrname:阿努拉德普勒
[ATM 2],atmbrno:ATM084},{atmbrname:马纳尔分校
,atmbrno:类型org.json.JSONArray的ATM344}]无法转换
到的JSONObject

什么是错在这种情况下?

下面是我调用类

 公共类ListAtmActivity扩展ListActivity {私有静态字符串URL =htt​​p://10.0.2.2:8080/hello/AvailabilityResponse;// TextView的错误;
//字符串brName;//包B = getIntent()getExtras()。
//字符串brName = b.getString(钥匙);私有静态最后弦乐TAG_CONTACTS =接触;
私有静态最后弦乐TAG_ID =ID;
私有静态最后弦乐ATM_NO =atmbrno;
私有静态最后弦乐ATM_PLACE =atmbrname;//接触JSONArray
// JSONArray接触= NULL;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.list_item);    字符串brName = getIntent()getExtras()的getString(密钥)。;
    / *包B = getIntent()getExtras()。
    brName = b.getString(钥匙);
    * /
    //为哈希映射的ListView
    ArrayList的<&HashMap的LT;字符串,字符串>> contactList =新的ArrayList<&HashMap的LT;字符串,字符串>>();    //创建JSON解析器实例
    JSONParser jParser =新JSONParser();    // URL从获取JSON字符串
    JSONObject的JSON = jParser.getJSONFromUrl(URL,brName);
    尝试{
        //字符串的结果;
        JSONArray接触= json.getJSONArray(TAG_CONTACTS);        的for(int i = 0; I< contacts.length();我++){
            JSONObject的json_data = contacts.getJSONObject(I)            //存储在变量中的每个JSON项目
            字符串atm_id = json_data.getString(ATM_NO);
            字符串atm_name = json_data.getString(ATM_PLACE);            HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();            map.put(ATM_NO,atm_id);
            map.put(ATM_PLACE,atm_name);            contactList.add(地图);
        }
    }    赶上(JSONException E){
        e.printStackTrace();    }    / **
     *更新解析JSON数据到ListView控件
     * * /
   ListAdapter适配器=新SimpleAdapter(这一点,contactList,
            R.layout.list_main,
            新的String [] {ATM_NO,ATM_PLACE},新的INT [] {
                    R.id.name,R.id.email});    setListAdapter(适配器);}}


解决方案

您可以JSON对象变成JSON数组,

 公共类JSONParser {静态InputStream为= NULL;
静态JSONArray jObj = NULL;
静态JSON字符串=;//构造
公共JSONParser(){}    公共JSONArray getJSONFromUrl(URL字符串,字符串一){        ArrayList的<&的NameValuePair GT; postParameters =新的ArrayList<&的NameValuePair GT;();
        postParameters.add(新BasicNameValuePair(分支名称,一));        尝试{
            // defaultHttpClient
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HttpPost httppost =新HttpPost(URL);
            httppost.setEntity(新UrlEn codedFormEntity(postParameters));            HTT presponse HTT presponse = httpClient.execute(httppost);
            HttpEntity httpEntity = HTT presponse.getEntity();
            是= httpEntity.getContent();        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON数组
        尝试{
            jObj =新JSONArray(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }
        返回jObj;
}}

您返回的数据是JSON数组,但你转换JSON对象,这是唯一的例外加薪。

 静态JSONArray jObj = NULL;   //尝试分析字符串到一个JSON数组
    尝试{
        jObj =新JSONArray(JSON);
    }赶上(JSONException E){
        Log.e(JSON解析器,错误分析数据+ e.toString());
    }

I want to create json object from a string that comes as a response from a servlet in my server.

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

    public JSONObject getJSONFromUrl(String url,String a) {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("branchname", a));

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            HttpResponse httpResponse = httpClient.execute(httppost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;            
}}

This is my servlet..

public class AvailabilityResponse extends HttpServlet {

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

    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+"'");
        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);
}

    catch(Exception e){
            out.print(e);
    }


}}

but when I run this it says Error

"parsing data org.json.JSONException: Value [{"atmbrname":"ANURADAPURA
[ATM 2]","atmbrno":"ATM084"},{"atmbrname":"MANNAR BRANCH  
","atmbrno":"ATM344"}] of type org.json.JSONArray cannot be converted
to JSONObject"

what is the wrong in this case?

Here is my calling class

public class ListAtmActivity extends ListActivity{

private static String url ="http://10.0.2.2:8080/hello/AvailabilityResponse";

//TextView error;
//String brName;

//Bundle b = getIntent().getExtras();
//String brName = b.getString("key");

private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String ATM_NO = "atmbrno";
private static final String ATM_PLACE = "atmbrname";

// contacts JSONArray
//JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);

    String brName=getIntent().getExtras().getString("key");


    /*Bundle b = getIntent().getExtras();
    brName = b.getString("key");
    */


    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url,brName);


    try{
        //String results;
        JSONArray contacts = json.getJSONArray(TAG_CONTACTS);

        for(int i = 0; i < contacts.length(); i++){
            JSONObject json_data = contacts.getJSONObject(i);

            // Storing each json item in variable
            String atm_id = json_data.getString(ATM_NO);
            String atm_name = json_data.getString(ATM_PLACE);

            HashMap<String, String> map = new HashMap<String, String>();

            map.put(ATM_NO, atm_id);
            map.put(ATM_PLACE, atm_name);

            contactList.add(map);                
        }                       
    }

    catch(JSONException e) {
        e.printStackTrace();

    }

    /**
     * Updating parsed JSON data into ListView
     * */
   ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_main,
            new String[] { ATM_NO, ATM_PLACE }, new int[] {
                    R.id.name , R.id.email });

    setListAdapter(adapter);

}}

解决方案

you can change json object to json array,

  public class JSONParser {

static InputStream is = null;
static JSONArray jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

    public JSONArray getJSONFromUrl(String url,String a) {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("branchname", a));

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            HttpResponse httpResponse = httpClient.execute(httppost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON Array
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;            
}}

Your return data is json array, but you convert json object ,that's only Exception raise.

  static JSONArray jObj = null;

   // try parse the string to a JSON Array
    try {
        jObj = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

这篇关于字符串转换为一个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆