将xml转换为json并提取数据

时间:2020-12-26 16:33:20

I have to extract some data from json.

我必须从json中提取一些数据。

After HTTP GET I convert my xml ( site provides xml only) to json.

在HTTP GET之后,我将我的xml(site仅提供xml)转换为json。

When I try to extract data from json I got an error.

当我尝试从json中提取数据时,我收到了一个错误。

Some Advice ? Thanks in advance

一些忠告 ?提前致谢

Xml --> <data> <user id = "value" name="value" surname = "value" /> </data>

Xml - >

After conversion I have something like that

转换后,我有类似的东西

 Json --> {"data":{"user":[{"id":"value","name":"value","surname":"value"}]}}



   void convert(){
    String xml; //data from  HTTP GET                       
            JSONObject jsonObj = null;
            JSONObject data = jsonObj.getJSONObject("data");
            Log.d("JSON LOG","DATA: " + data.toString());
            try{

                jsonObj = XML.toJSONObject(xml);


                JSONArray jArray = jsonObj.getJSONArray("user");

                for (int i = 0 ; i < jArray.length(); i++){

                    JSONObject jsonObject = jArray.getJSONObject(i);

                    String id = jsonObject.getString("id");

                    Log.d("JSON LOG","ID: " + id);
                   String name = jsonObject.getString("name");

                    Log.d("JSON LOG","NAME: " + name);
                String sname = jsonObject.getString("surname");

                    Log.d("JSON LOG","SNAME: " + sname);

          }catch(JSONException e){
            Log.e("JSON Exception",e.getMessage());
            e.printStackTrace();

        }

    }//end void

I got the following error from catch ---> E/JSON Exception: No value for user

我从catch ---> E / JSON异常得到以下错误:没有用户的值

1 个解决方案

#1


1  

Add the following line before JSONArray jArray = jsonObj.getJSONArray("user");

在JSONArray之前添加以下行jArray = jsonObj.getJSONArray(“user”);

JSONObject jObj1 = jsonObj.getJSONObject("data");

Your user JSONArray is inside a JSONObject data.

您的用户JSONArray位于JSONObject数据中。

#1


1  

Add the following line before JSONArray jArray = jsonObj.getJSONArray("user");

在JSONArray之前添加以下行jArray = jsonObj.getJSONArray(“user”);

JSONObject jObj1 = jsonObj.getJSONObject("data");

Your user JSONArray is inside a JSONObject data.

您的用户JSONArray位于JSONObject数据中。