为什么我收到错误消息值<! - ?类型java.lang.String的xml无法转换为JSONObject? - >

时间:2012-06-25 09:44:39

标签: android json

我使用JSON创建了一个Web服务,我想解析它然后将它们放在listview上。但是当我运行应用程序时,它强制关闭并显示错误消息。请查看我的代码,有什么问题吗?

当我尝试运行我的应用程序时,以下是错误消息:

org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject

这是我的代码:

public class WeeklyFlashActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        JSONObject json = JSONfunctions.getJSONfromURL("http://www.greenfields.co.id:502/Service1.svc/json/weeklyflash");

        try{

            JSONArray  weeklyflash = json.getJSONArray("GetReportResult");

            for(int i=0;i<weeklyflash.length();i++){                        
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = weeklyflash.getJSONObject(i);

                //map.put("type",  String.valueOf(i));
                map.put("type", e.getString("type"));
                map.put("total", e.getString("total"));

                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                        new String[] { "type", "total" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(WeeklyFlashActivity.this, "Type " + o.get("type") + " was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }
}

这是我的JSON变量:

{"GetReportResult":[{"total":"249319","type":"ESL500ML"},{"total":"19802","type":"CHEESE1K"},{"total":"3179380","type":"ESL"},{"total":"201243","type":"WHP"},{"total":"736744.136","type":"UHT"}]}

这是我的JSON功能:

public class JSONfunctions {
    public static JSONObject getJSONfromURL(String url){

        //initialize
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            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);
            StringBuilder sb = new StringBuilder();
            String line = null;
            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());
        }

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

        return jArray;
    }

}

更新:我检查了我的结果,结果是一个HTML代码,并说Method not allowed.问题可能来自我的wcf服务。你对此有什么解决方案吗?

这是我的wcf服务:

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/json/weeklyflash")]

4 个答案:

答案 0 :(得分:6)

很多人都遇到过这个错误。可以通过更改charSet来解决它。尝试使用UTF-8而不是iso-8859-1。

更改以下行:

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);

答案 1 :(得分:2)

最后我解决了我自己的问题,问题出在我的http连接方法上,在我最近的帖子中,它使用HttpPost而我的wcf服务方法是GET,这就是我从wcf得到错误的原因提供Method not allowed

的服务

所以我通过http HttpGet更改我的http方法来找到解决方案,如下所示:
HttpGet httpget = new HttpGet(url);

它对我来说很好。感谢所有评论我的问题答案的人:)

答案 2 :(得分:1)

看起来你正在使用HttpPost方法从serer获取数据

        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);

但是根据错误Method not allowed.

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/json/weeklyflash")]

1-看起来你应该使用HttpGet而不是HttpPost。

2-使用response.getStatusLine()。getStatusCode()== HttpStatus.SC_OK或200(OK)和其他来处理响应,如

HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
     inst statusCode= statusLine.getStatusCode();
    if( statusCode== HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        //..more logic
    }else if(statusCode == HttpStatus.SC_BAD_REQUEST){
             //error bad request shoe message BAD_REQUEST

       }else if(statusCode == HttpStatus.SC_BAD_GATEWAY){
             //error bad request shoe message BAD_GATEWAY

       }     

以及更多,但all不是必须只有HttpStatus.SC_OK才是重要的...

答案 3 :(得分:-2)

Questioion: 值类型java lang string无法转换为jsonobject

答案: 这项工作正常 BufferedReader reader = new BufferedReader(new InputStreamReader(is,“iso-8859-1”),8); 到

BufferedReader reader = new BufferedReader(new InputStreamReader(is,“UTF-8”),8);