GVKun编程网logo

android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray

12

对于想了解android–解析数据时出错org.json.JSONException:值的读者,本文将是一篇不可错过的文章,并且为您提供关于AndroidJSON解析错误无法转换为JSONArray、

对于想了解android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray的读者,本文将是一篇不可错过的文章,并且为您提供关于Android JSON解析错误无法转换为JSONArray、Android json错误com.google.gson.JsonSyntaxException:java.lang.IllegalStateException、android – Gson中的RuntimeException解析JSON:无法调用受保护的java.lang.ClassLoader()而没有args、android – JSONArray无法转换为JSONObject错误的有价值信息。

本文目录一览:

android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray

android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray

我正在编写一个打算在 Android设备上运行的应用程序.应用程序通过PHP读取MysqL数据库中的信息,但是当我运行应用程序时,Log cat会提示错误’错误解析数据org.json.JSONException:Value

我得到的代码是从教程中下载的,请耐心等待我已经掌握了一些基本的PHP知识和很少的java知识.我已经测试了PHP脚本,它运行完美,所以我不会费心去附上它.

main.java代码:

 package test.an2MysqL;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


public class main extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources 
    // but since its an example saves declaring them in the XML. 
    LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
    txt = new TextView(getApplicationContext()); 
    rootLayout.addView(txt); 
    setContentView(rootLayout); 

    // Set the text and call the connect function. 
    txt.setText("Connecting...");
  //call the method to run the data retreival
    txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://10.1.1.19/cms/test/android2MysqL/read.PHP"; //i use my real ip here



private String getServerData(String returnString) {

   InputStream is = null;

   String result = "";
    //the data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("country","undefined"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            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());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ",country: "+json_data.getString("country")+
                            ",documentn: "+json_data.getInt("documentn")
                    );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);
       }
    }catch(JSONException e){
            Log.e("log_tag","Error parsing data "+e.toString());
    }
    return returnString;
}   

}

我很感激你能给我的任何帮助.

解决方法

正如您对问题的评论中所指出的那样,您的服务器似乎正在返回XML而不是JSON.您只需输出结果即可轻松确认:

}catch(JSONException e){
    Log.e("log_tag","Error parsing data "+e.toString());
    Log.e("log_tag","Failed data was:\n" + result);
}

如果它是XML,它几乎肯定是必须的,那么你需要让服务器输出JSON,或者你需要解析它发送给你的XML.

Android JSON解析错误无法转换为JSONArray

Android JSON解析错误无法转换为JSONArray

我是Android开发人员的新手,我正在尝试编写一个程序来解析网站中的一些JSON并将其输出到ListView中.但是,当我运行我的程序时,我收到错误:(有超过7行与此错误相同)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/Failed: Json parsing
error: Value
{“0″:”2″,”id”:”2″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-01″,”date”:”2017-04-01″,”4″:”20″,”hour”:”20″}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/Failed: Json parsing error:
Value
{“0″:”3″,”id”:”3″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-08″,”date”:”2017-04-08″,”4″:”20″,”hour”:”20″}
of type org.json.JSONObject cannot be converted to JSONArray

我试图解析的JSON是:

{“appointments”:[{“0″:”2″,”id”:”2″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-01″,”date”:”2017-04-01″,”4″:”20″,”hour”:”20″},{“0″:”3″,”id”:”3″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-08″,”date”:”2017-04-08″,”4″:”20″,”hour”:”20″},{“0″:”4″,”id”:”4″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-15″,”date”:”2017-04-15″,”4″:”20″,”hour”:”20″},{“0″:”5″,”id”:”5″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-04-22″,”date”:”2017-04-22″,”4″:”20″,”hour”:”20″},{“0″:”6″,”id”:”6″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-03-24″,”date”:”2017-03-24″,”4″:”17″,”hour”:”17″},{“0″:”7″,”id”:”7″,”1″:”0″,”cid”:”0″,”2″:”1″,”uid”:”1″,”3″:”2017-03-26″,”date”:”2017-03-26″,”4″:”17″,”hour”:”17″},{“0″:”8″,”id”:”8″,”1″:”1″,”cid”:”1″,”2″:”1″,”uid”:”1″,”3″:”2017-03-26″,”date”:”2017-03-26″,”4″:”16″,”hour”:”16″},{“0″:”9″,”id”:”9″,”1″:”2″,”cid”:”2″,”2″:”1″,”uid”:”1″,”3″:”2017-03-26″,”date”:”2017-03-26″,”4″:”15″,”hour”:”15″},{“0″:”10″,”id”:”10″,”1″:”3″,”cid”:”3″,”2″:”1″,”uid”:”1″,”3″:”2017-03-26″,”date”:”2017-03-26″,”4″:”13″,”hour”:”13″}]}

这是我的listview自定义行java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("Failed", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

这是json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_appointments);

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printstacktrace();
        }
    }
}

如果我不解析:

enter image description here

解决方法:

您的所有数据都包含以下数据.如下所示.

 alldata={"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}

所以每次你的列表项从该约会数组中获取数据.所以alldata变量将根据getItem(position)方法的位置进行更改.

所以,alldata是jsonObject.

所以你应该解析如下,

 JSONObject jsonRowData= new JSONObject(allData);
 try{
   jsonRowData.getString("0");
   jsonRowData.getString("id"):
   jsonRowData.getString("1"):
   jsonRowData.getString("cid"):
   jsonRowData.getString("2"):
   jsonRowData.getString("uid"):
   jsonRowData.getString("3");
   jsonRowData.getString("date"):
   jsonRowData.getString("4");
    }catch(Exception e){
    e.printstacktrace();
   }

就像你必须打电话.希望能帮助到你

Android json错误com.google.gson.JsonSyntaxException:java.lang.IllegalStateException

Android json错误com.google.gson.JsonSyntaxException:java.lang.IllegalStateException

我在解析json数据时遇到此错误

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

我无法找到解决方案.我的json数据是:

{
  "user": [
    {
      "email": "wijden@jerseyrest.com",
      "firstName": "Wijden",
      "id": "1",
      "lastName": "User"
    }, {
      "email": "user@jerseyrest.com",
      "firstName": "Sample",
      "id": "2",
      "lastName": "User"
    }, {
      "email": "ingenieur@jerseyrest.com",
      "firstName": "Ingenieur",
      "id": "3",
      "lastName": "User"
    }
  ]
}

这就是我做到的方式:

Type type = new Typetoken<List<WorkItem>>() { }.getType();
List<WorkItem> workitems = (List<WorkItem>) new Gson().fromJson(resultat, type);

如果你能帮助我解决问题,我将不胜感激.提前致谢

解决方法:

为了解析你的JSON,我创建了包装响应的类,即:

public class Response {
  @Serializedname("user")
  private List<User> userList;
  //getters and setters
}

和,

public class User{
  @Serializedname("id")
  private int id;
  @Serializedname("email")
  private String email;
  @Serializedname("firstName")
  private String firstName;
  @Serializedname("lastName")
  private String lastName;
  //getters and setters
}

然后,为了解析您的JSON响应,您只需要:

Gson gson = new Gson();
Response data = gson.fromJson(yourjsonString, Response.class);

然后,您可以非常轻松地访问您的数据,例如:

User user = data.getUserList.get(i);

注意:使用注释@Serializedname对于分离JSON响应中和应用程序中的字段名称很有意义,以便遵循Java命名约定…

android – Gson中的RuntimeException解析JSON:无法调用受保护的java.lang.ClassLoader()而没有args

android – Gson中的RuntimeException解析JSON:无法调用受保护的java.lang.ClassLoader()而没有args

我继承了一些代码,使用Gson将我们的应用程序状态保存为 JSON,然后使用 fromJson读取它.
Gson gson = createGson();
gson.fromJson(objString,myClass);

其中一个保存的字段是Location.不幸的是,很有可能解析保存的数据失败,因为我保存的Location在其mExtras中包含一个mClassLoader,而Gson库无法使用此错误创建ClassLoader:

RuntimeException: Failed to invoke protected java.lang.classLoader() with no args

有谁知道为什么ClassLoader被包含在我的Location的附加内容中,以及它是否应该以JSON表示结尾?

我假设我可以通过单独保存位置对象中的关键字段(例如经度,纬度,高度,时间,精度)来解决这个问题,但如果可能的话,保存位置对象会很好.

我看到有一个ExclusionStrategy对象可用于排除字段,但我不确定是否可以/应该使用它来排除我位置内的额外内容…

仅供参考,这是我的Location对象的JSON数据(经度和纬度改为隐藏我):

{
    <snip>
    "lastKNownLocation": {
        "mResults": [
            0,0
        ],"mProvider": "gps","mExtras": {
            "mParcelledData": {
                "mOwnObject": 1,"mObject": 5525040
            },"mClassLoader": {
                "packages": {}
            },"mMap": {},"mHasFds": false,"mFdsKNown": true,"mAllowFds": true
        },"mdistance": 0,"mTime": 1354658984849,"mAltitude": 5.199999809265137,"mLongitude": -122.4376,"mLon2": 0,"mLon1": 0,"mLatitude": 37.7577,"mLat1": 0,"mLat2": 0,"mInitialbearing": 0,"mHasspeed": true,"mHasbearing": false,"mHasAltitude": true,"mHasAccuracy": true,"mAccuracy": 16,"mSpeed": 0,"mbearing": 0
    },<snip>
}

下面是代码未崩溃时mExtras包含的示例:

"mExtras": {
    "mParcelledData": {
        "mOwnsNativeParcelObject": true,"mNativePtr": 1544474480
    },"mAllowFds": true
}

解决方法

问题是你试图直接将系统提供的类(Location)转换为JSON.而且,正如您所看到的,在序列化内部状态/ Java特定事物时会遇到问题. JSON是一种传递信息的半通用方式.

你不能轻易使用@Expose注释,因为它不是你的类;这将需要修改Location的源代码或通过使用jassist在运行时添加它们的相当广泛的过程(参见:http://ayoubelabbassi.blogspot.com/2011/01/how-to-add-annotations-at-runtime-to.html)

查看Location类,我只需创建一个自定义Gson Serializer和Deserializer并完成它.你真正感兴趣的是GPS数据,而不是类本身的内部.您只需使用getter构建包含序列化程序中所需信息的JSON,然后在Deserializer中创建一个新的Location实例,并使用公共setter从提供的JSON中填充信息.

class LocationSerializer implements JsonSerializer<Location>
{
    public JsonElement serialize(Location t,Type type,JsonSerializationContext jsc)
    {
        JsonObject jo = new JsonObject();
        jo.addProperty("mProvider",t.getProvider());
        jo.addProperty("mAccuracy",t.getAccuracy());
        // etc for all the publicly available getters
        // for the information you're interested in
        // ...
        return jo;
    }

}

class LocationDeserializer implements JsonDeserializer<Location>
{
    public Location deserialize(JsonElement je,JsonDeserializationContext jdc)
                           throws JsonParseException
    {
        JsonObject jo = je.getAsJsonObject();
        Location l = new Location(jo.getAsJsonPrimitive("mProvider").getAsstring());
        l.setAccuracy(jo.getAsJsonPrimitive("mAccuracy").getAsFloat());
        // etc,getting and setting all the data
        return l;
    }
}

现在在您的代码中使用GsonBuilder并注册类:

...
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Location.class,new LocationDeserializer());
gsonBuilder.registerTypeAdapter(Location.class,new LocationSerializer());
Gson gson = gsonBuilder.create(); 
...

这应该照顾它.

android – JSONArray无法转换为JSONObject错误

android – JSONArray无法转换为JSONObject错误

在获取json数据时,我收到错误:

JSONArray cannot be converted to JSONObject

生成json的代码:

JSONObject parent = new JSONObject();
DatabaseHandler dbh = new DatabaseHandler(getApplicationContext());  
            for(int i=0; i < allEds.size(); i++){
                String edsText = allEds.get(i).getText().toString();                                           
               //spinner = allSpns.get(i);
               String spinSelected=allSpns.get(i).getSelectedItem().toString();                  
               try
                {
                   JSONObject json = new JSONObject();          
                   json.put("Id", i);
                   json.put("FieldName", edsText);
                   json.put("FieldType",spinSelected);
                   parent.accumulate("data", json);



                }
                catch (JSONException e)
                {
                        // Todo Auto-generated catch block
                        e.printstacktrace();
                }                   

            }
Generated json is   
            {"data":
[{"FieldType":"Account Number","FieldName":"r","Id":0},
  {"FieldType":"Net      Banking Id","FieldName":"tt","Id":1}
 ]}
code for json read
------------------
JSONObject jsonObj = new JSONObject(folderStructure);
        JSONObject data = jsonObj.getJSONObject("data"); 
        String id = data.getString("Id"); 
        String value = data.getString("FieldName"); 
        Log.d("Item name: ", value);    

在阅读上面的json时遇到错误
代码有什么问题吗?

解决方法:

更改

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

JSONArray data = jsonObj.getJSONArray("data");

由于数据的值是JsonArray而不是JSONObject.

要获取单个ID和字段名称,您应该遍历此JSONArray,如下所示:

for(int i=0; i<data.length(); i++)
{
     JSONObject obj=data.getJSONObject(i);
     String id = obj.getString("Id"); 
        String value = obj.getString("FieldName"); 
        Log.d("Item name: ", value);
}

我们今天的关于android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray的分享就到这里,谢谢您的阅读,如果想了解更多关于Android JSON解析错误无法转换为JSONArray、Android json错误com.google.gson.JsonSyntaxException:java.lang.IllegalStateException、android – Gson中的RuntimeException解析JSON:无法调用受保护的java.lang.ClassLoader()而没有args、android – JSONArray无法转换为JSONObject错误的相关信息,可以在本站进行搜索。

本文标签: