XML 在 android 中解析

XML parse in android

我正在尝试解析一个 .net 服务,其中 return 数据采用 xml 格式,来回使用 json 但未获取实际数据。 我收到错误消息

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

这是我的 XML 格式的响应

<?xml version="1.0" encoding="utf-8"?>   

<string xmlns="http://tempuri.org/">

[
  {
        "SHAPE":"xyz",
        "COLOR":"E",
        "CLARITY":"pqr",
        "STONEID":"93",
        "DISC_PER":34000,
        "ASKAMT_FC":245,
        "POLISH":"xxx",
        "SYM":"EX"
        },
        {
        "SHAPE":"pqr",
        "COLOR":"f",
        "CLARITY":"xyz",
        "STONEID":"987",
        "DISC_PER":34000,
        "ASKAMT_FC":245,
        "POLISH":"xxx",
        "SYM":"EX"
    }
]
</string>

这是我的 main.class

public class MainActivity extends AppCompatActivity {
ArrayList<getdataoflist> eventlistsubcat;
String response;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new AsyncVideo().execute();
}
public class AsyncVideo extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... params) {

        String shape="";
        String color1 = "";
        String clarity = "";
        String cts = "";
        String stone = "";
        String discper = "";
        String askamt = "";
        String certificate = "";
        String cut = "";
        String polish = "";
        String sym = "";
        String certyno="";
        String stoid="";
        String bsone="";
        Uri.Builder builder = new Uri.Builder()
                .appendQueryParameter("pshape", shape)
                .appendQueryParameter("pcolor", color1)
                .appendQueryParameter("pcts", clarity)
                .appendQueryParameter("pcerty", cts)
                .appendQueryParameter("pcut", stone)
                .appendQueryParameter("ppolish", discper)
                .appendQueryParameter("pclarity", askamt)
                .appendQueryParameter("psymm", certificate)
                .appendQueryParameter("pflour", cut)
                .appendQueryParameter("pnarrival",polish)
                .appendQueryParameter("p3ex",sym)
                .appendQueryParameter("pcertyno",certyno)
                .appendQueryParameter("pstoneid",stoid)
                .appendQueryParameter("pprebookcertifiedstones",bsone);

        HttpHandler parser = new HttpHandler();
        response = parser.makePostServiceCall( StaticDataUtility.Server_URL,builder,parser.POST);


        JSONObject root = null;

       if (response != null) {
            eventlistsubcat = new ArrayList<getdataoflist>();
            try {
               // root = new JSONObject(response);
                JSONArray jsonArray=new JSONArray(response);
                    JSONObject c = jsonArray.getJSONObject(0);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        c = jsonArray.getJSONObject(i);
                        eventlistsubcat.add(new getdataoflist(c.getString("SHAPE"), c.getString("COLOR"), c.getString("CLARITY"), c.getString("STONEID"), c.getString("DISC_PER"), c.getString("ASKAMT_FC"), c.getString("POLISH"), c.getString("SYM")));
                    }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return response;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}

}

这是我的 handler.class

public class HttpHandler {
static String response = null;
public static final int GET = 1;
public static final int POST = 2;
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url = null;

public HttpHandler(){

}

public String makeGetServiceCall(String reqUrl, int method) {

    if (method == GET) {

        try {
            url = new URL(reqUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(50000);
            connection.setRequestMethod("GET");
            connection.connect();

            int status = connection.getResponseCode();

            if (status == 200) {

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = "";

                while ((line = reader.readLine()) != null) {

                    builder.append(line);
                }

                response = builder.toString();

            }else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                Log.e("reader",reader.toString());
            }


        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return response;

}



public String makePostServiceCall(String reqUrl, Uri.Builder params, int method) {

    if (method == POST) {

        try {
            url = new URL(reqUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(50000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            String query = params.build().getEncodedQuery();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            writer.write(query);
            writer.flush();
            writer.close();

            connection.connect();

            int status = connection.getResponseCode();

            if (status == 200) {

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = "";

                while ((line = reader.readLine()) != null) {

                    builder.append(line);
                }

                response = builder.toString();

            }else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                Log.e("reader",connection.getErrorStream().toString());
            }


        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return response;

}

}

如果你想解析 XML 文件中的 json 数据,那么你需要得到 json 这样的字符串

 private void getSubString(){
        String myresponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?>   \n" +
                "<string xmlns=\"http\">\n" +
                "[\n" +
                "  {\n" +
                "        \"SHAPE\":\"xyz\",\n" +
                "        \"COLOR\":\"E\",\n" +
                "        \"CLARITY\":\"pqr\",\n" +
                "        \"STONEID\":\"93\",\n" +
                "        \"DISC_PER\":34000,\n" +
                "        \"ASKAMT_FC\":245,\n" +
                "        \"POLISH\":\"xxx\",\n" +
                "        \"SYM\":\"EX\"\n" +
                "        },\n" +
                "        {\n" +
                "        \"SHAPE\":\"pqr\",\n" +
                "        \"COLOR\":\"f\",\n" +
                "        \"CLARITY\":\"xyz\",\n" +
                "        \"STONEID\":\"987\",\n" +
                "        \"DISC_PER\":34000,\n" +
                "        \"ASKAMT_FC\":245,\n" +
                "        \"POLISH\":\"xxx\",\n" +
                "        \"SYM\":\"EX\"\n" +
                "    }\n" +
                "]\n" +
                "</string>";


        myresponse = myresponse.substring(myresponse.indexOf("["),myresponse.lastIndexOf("]")+1);
    }

现在您可以轻松地从 myresponse 解析 json,因为它不包含 XML 标签。

见附上的有效屏幕截图 json。