java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行列是 STRING
Posted
技术标签:
【中文标题】java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行列是 STRING【英文标题】:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 【发布时间】:2018-07-28 11:00:11 【问题描述】:我正在学习 parcing,但在尝试实现它时遇到了问题。 发现了很多类似的问题和更多的解决方案,但没有任何帮助我
那是我的 json
"firstName": "name",
"lastName": "last",
"resistances":
"a1": 1,
"a2": 2,
"a3": 3,
"a4": 4
播放器类
class Player implements Serializable
String firstName;
String lastName;
int[] resistances;
public Player(String firstName, String lastName, int[] resistances)
this.firstName = firstName;
this.lastName = lastName;
this.resistances = resistances;
以及我如何尝试分配
Gson gson = new Gson();
Player player = gson.fromJson("test.json", Player.class);
求救
【问题讨论】:
第三个变量将是一个对象.. 阻力.. 和最外层的json pbj必须有名字.. 如果“resistances”是一个数组,它应该是:“resistances”: [ 1, 2, 3, 4 ] 所以错误消息是因为它正在查找字符串“a1” 【参考方案1】:fromJson(String, Class) 解析字符串本身,在您的情况下为test.json
,而不是它所代表的文件。您需要从您尝试解析的文件中创建一个 Reader 并将其作为第一个参数传递。
如果 test.json 在外部存储中:
String fpath = Environment.getExternalStorageDirectory() + "/path/to/test.json";
try
FileReader fr = new FileReader(fpath));
gson.fromJson(fr, Player.class);
catch (Exception e1)
e1.printStackTrace();
【讨论】:
我会从一开始就这样做,但这取决于文件的位置。如果test.json
在raw
资源文件夹中,您可以使用new InputStreamReader(getResources().openRawResource(R.raw.test))
(忽略扩展名)。如果是在sd卡上,答案就长了一点。
非常感谢!它的工作!还有一个问题 - 将 .json 文件放入 assets 文件夹或 raw 有什么区别?
这里解释一下***.com/questions/9563373/…
tyvm 又来了!我可以给你+业力吗? :D【参考方案2】:
您的 JSON“阻力”对象应如下所示,以便您的解析代码正常工作:
"firstName": "name",
"lastName": "last",
"resistances": [
1, 2, 3, 4
]
或者,将 Java 中的电阻变量更改为 Map。 Look here for a previous answer - GSON 可以将字典 JSON 对象解析为 Map。
class Player implements Serializable
String firstName;
String lastName;
Map<String, Integer> resistances;
public Player(String firstName, String lastName, Map<String, Integer> resistances)
this.firstName = firstName;
this.lastName = lastName;
this.resistances = resistances;
【讨论】:
以上是关于java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行列是 STRING的主要内容,如果未能解决你的问题,请参考以下文章