android - 返回值为 null 的 json 响应。

标签 android json

我正在为一个文件写一个 JSON 响应,当我从文本文件中检索它时,它在 json 对象之前有一个空值(真的很奇怪)。

05-30 16:35:16.454: W/System.err(21734): org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
05-30 16:35:16.454: W/System.err(21734):    at org.json.JSON.typeMismatch(JSON.java:111)
05-30 16:35:16.454: W/System.err(21734):    at org.json.JSONObject.<init>(JSONObject.java:158)
05-30 16:35:16.454: W/System.err(21734):    at org.json.JSONObject.<init>(JSONObject.java:171)

然后在打印字符串时显示它。

05-30 16:35:16.454: I/json data in ProfileActivity(21734): null{"id":1488,"email":"xxx@xxx.com","full_name":"Jon

这是我保存和检索数据的方式。

public void saveToInternal(String data, String name, Context context){
      ContextWrapper contextWrapper = new ContextWrapper(context);
      File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
      myInternalFile = new File(directory , name);
      try {
            FileOutputStream fos = new FileOutputStream(myInternalFile);
            fos.write(data.getBytes());
            fos.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
      Log.i("data saved", "data named " + name + "saved to directory.");
}

public String getInternalData(String filename, Context context){
      ContextWrapper contextWrapper = new ContextWrapper(context);
      File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
      myInternalFile = new File(directory , filename);
    String myData = null;
     try {
            FileInputStream fis = new FileInputStream(myInternalFile);
            DataInputStream in = new DataInputStream(fis);
            BufferedReader br = 
             new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
             myData = myData + strLine;
            }
            in.close();
           } catch (IOException e) {
            e.printStackTrace();
           }

    return myData;

}

最佳答案

我想通了!

我改了行:

String myData = null;

到:

String myData = "";

myData 被附加到另一个字符串,但是如果您将一个空值附加到一个字符串,您会在数据的前面得到一个奇怪的不可移除的空值。

关于android - 返回值为 null 的 json 响应。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840376/

相关文章:

php - json_decode 无法读取以 json 格式存储数据的文本文件

arrays - 我正在尝试使用 v : structure 解析来自 zendesk 的 json 数据

JSON 序列化与 XPath 3.1 fn :serialize

java - 在对话框内的 editText 中隐藏键盘

android - 泛化异常处理 Retrofit

android - Android Wear 2.0架构问题带来的实时复杂性

java - 将 json 格式的参数数组传递给 SOAP Web 服务?

android - 在两个标记 map-box react-native 之间画一条线?

android - Adapter在android中的使用

java - Log4J - JsonLayout 和 RollingFileAppender 生成无效的 JSON