0

我用 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")]

很多人都遇到过这个错误。它可以通过更改 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);
4

4 回答 4

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);
于 2012-06-25T10:05:36.147 回答
2

最后我解决了自己的问题,问题出在我的 http 连接方法上,在我最近的帖子中,它使用HttpPost了,而我的 wcf 服务方法是GET,这就是为什么我从 wcf 服务收到错误消息Method not allowed

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

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

于 2012-06-26T02:57:23.610 回答
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

       }     

还有更多但并非全部都必须只有 HttpStatus.SC_OK 是重要的一个...

于 2012-06-26T03:57:02.570 回答
-2

问题:java lang字符串类型的值无法转换为jsonobject

答案:正确执行此工作 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 到

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

于 2017-04-17T05:50:00.393 回答