【问题标题】:extract jsonarray from xml string从xml字符串中提取jsonarray
【发布时间】:2015-10-06 07:12:33
【问题描述】:

我正在尝试使用 asynctask 通过 http post 方法调用 url 链接。如果链接是“http://example.com/broadcast/”,我正在将参数传递给类似我正在添加“name=ravi/age=30/”这样的参数。该操作正在工作,因为获得了输出,但我得到的响应是包含 JSONArray 的 xml 字符串格式。我只想从 xml 字符串中提取 JSONArray 输出。

webResponse output:

<?xml version="1.0"  
encoding="utf-8"?>
<string xmlns="https://example.com/statement">

[{"status":"ok","code":"pass"}]</string>
public class HttpPostExample extends Activity {

	
	
    /** Called when the activity is first created. */ 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_post_example);
        
    Button saveme=(Button)findViewById(R.id.save);
    saveme.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		
        			
        		new AsyncCallWS().execute();
        		
        	}
     });  
  } //oncreate
    
private class AsyncCallWS extends AsyncTask<String, Void, String> {
    	
    	
    	
		@Override
        protected void onPreExecute() {
            
    		

        }

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			String webResponse=""; 
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://example.com/going.asmx/broadcast?"); 

			//Post Data
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
			nameValuePair.add(new BasicNameValuePair("alpha", "A1B2C3"));
			nameValuePair.add(new BasicNameValuePair("type", "IN"));
			nameValuePair.add(new BasicNameValuePair("name", "Somnath"));
			nameValuePair.add(new BasicNameValuePair("bind", "Hour Glass"));
			nameValuePair.add(new BasicNameValuePair("body", "Hundo"));

			//Encoding POST data
			try{
					httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			}catch (UnsupportedEncodingException e) {
	
				e.printStackTrace();
				System.out.println(e);
			}

			//making POST request.
			try{
					HttpResponse response = httpClient.execute(httpPost);
					webResponse = EntityUtils.toString(response.getEntity());
				
					
					
			}catch (ClientProtocolException e) {
				// Log exception
				e.printStackTrace();
				System.out.println(e);
			} catch (IOException e) {
				// Log exception
				e.printStackTrace();
				System.out.println(e);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		
		     
			return  webResponse;
		}
		
			@Override
	    protected void onPostExecute(String webResponse) {
	         
			   
				Toast.makeText(getApplicationContext(), webResponse, Toast.LENGTH_LONG).show();
	    }
	     
    } // AsyncTask ends
    
    
	

} //activity

【问题讨论】:

    标签: android json xml http-post


    【解决方案1】:

    尝试通过以下代码删除xml代码,并在postExecute中获取json数组:

        int first,second;
        first = webResponse.indexOf("[");
        second = webResponse.indexOf(first +1 , webResponse.length());
        String json = webResponse.substring(first, second);
        JSONObject jsonObj = new JSONObject(json);
        JSONArray array = jsonObj.getJSONArray("status");
    

    【讨论】:

    • 用于从androidhive.info/2012/01/android-json-parsing-tutorial下方的数组检查链接获取数据
    • “jsonStr”从何而来?它给出“无法解决变量错误”。
    • 我尝试这样获得至少 [{"status":"ok", "code":"pass"}],但出现错误“执行 doInBackground 时出错”和“原因: StringIndexOutOfBoundsException: length=126, regionStart=86, regionLength=-87
    • 使用的代码是:HttpResponse response = httpClient.execute(httpPost); String temp = EntityUtils.toString(response.getEntity()); int first,second; first = temp.indexOf("["); second = temp.indexOf(first +1 , temp.length()); webResponse = temp.substring(first, second); 然后我在onPostExecute中使用Toast来显示webResponse。
    • @sam ,使用我建议的代码,我认为它必须工作。我对其进行了编辑,并从中删除了“jsonStr”。
    【解决方案2】:

    我使用以下代码得到了所需的结果:

       HttpResponse response = httpClient.execute(httpPost);
    				String XmlString = EntityUtils.toString(response.getEntity());
    				XmlString=XmlString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
    				XmlString = XmlString.substring(XmlString.indexOf("[") + 1, XmlString.lastIndexOf("]"));
    				JSONObject jObj = new JSONObject(XmlString);
    				webResponse = jObj.getString("status");

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2013-05-02
      • 2013-07-22
      • 2013-08-28
      • 1970-01-01
      • 2013-12-10
      • 2016-06-30
      • 1970-01-01
      • 2014-08-30
      相关资源
      最近更新 更多