解析JSON对象,对象不是try块更新
我在大学的项目工作,我试图从出现这样的API解析时刻表信息:解析JSON对象,对象不是try块更新
"1474239600000" : {
"courseCode" : "CASE4",
"moduleCodes" : [ "CareersService" ],
"moduleDescription" : "Careers Svs. slots in ALL Year 4s",
"startTime" : 1474286400000,
"endTime" : 1474290000000,
"locations" : [ "GLA.XG21", "GLA.Q119" ],
"type" : "SEMINAR"
}
我正在解析Android活动的AsyncTask中的代码。这是我做了这样做的代码:
protected Lecture doInBackground(String... urls) {
Lecture lec = new Lecture();
try{
BufferedReader in = new BufferedReader(
new FileReader("json.txt"));
String inputLine;
String content = "";
while ((inputLine = in.readLine()) != null) {
content = content + inputLine;
System.out.println(inputLine);
//Log.d("INPUT:",inputLine);
}
JSONObject obj = new JSONObject(content);
String courseCode = obj.getString("courseCode");
String moduleDescription = obj.getString("moduleDescription");
String type = obj.getString("type");
lec = new Lecture(courseCode,"TEST",moduleDescription,type);
}catch(Exception e){
Log.e("JSON PARSER:","CATCH ERROR");
e.printStackTrace();
}
return lec;
}
当我返回讲座对象LEC,它没有显示在try块分配值,但被设置到演讲的默认值。
我希望得到任何帮助可能,
感谢, 瑞安。
您的JSON格式错误。改变你的JSON以下结构,那么你的代码应工作:
{
"courseCode" : "CASE4",
"moduleCodes" : [ "CareersService" ],
"moduleDescription" : "Careers Svs. slots in ALL Year 4s",
"startTime" : 1474286400000,
"endTime" : 1474290000000,
"locations" : [ "GLA.XG21", "GLA.Q119" ],
"type" : "SEMINAR"
}
一个JSON关键不能是JSON文件的根元素,这是你的情况“1474239600000”。正因为如此,您很可能会收到异常,因为无法创建JSONObject。
嗨@BrickTop我已经删除了JSON密钥,但我仍然无法进入try块 –
好的,您可以请发布完整的AsyncTask,您正在调用AsyncTask的活动以及json.txt的完整内容。另外如果有一个异常也发布StackTrace。你是否已经尝试调试它? – BrickTop
是您的问题中描述的JSON完成?如果是这样的话,它是畸形的。我假设你也得到一个异常,应用程序永远不会运行整个try块。 – BrickTop
你有什么想法,为什么这个应用程序没有进入try块吗? –
@BrickTop \t 你有什么想法,为什么这个应用程序没有进入try块吗? –