String json = "{'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'York'}";
try {
JSONObject jsonObject = JSONObject.fromObject(json);
String name = jsonObject.getString("name");
String address = jsonObject.getString("address");
System.out.println("name is:" + name);
System.out.println("address is:" + address);
JSONArray jsonArray = jsonObject.getJSONArray("array");
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println("item " + i + " :" + jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Eveything is OK.
But when I put {'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'York'} into a file.
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null){
JSONObject jo = JSONObject.fromObject(tempString.trim());
String id = jo.getString("id");
String name = jo.getString("name");
log.info(id + ":" + name);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
It tells me Exception in thread "main" net.sf.json.JSONException: A JSONObject text must begin with '{' at character 1 of "{'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'York'}. What's the problem in this code? Can any figure it out for me? Thanks.
my file:
{'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'York'}
EF BB BF. It may not matter in this case but you should use a Charset to specify an encoding to your Reader.idparameter in your JSON. You are tryingjo.getString("id")?