我只是尝试获取存储在我的JSON文件中的值并将其保存到sqlite数据库中:
这是我的JSON文件:
{
"list": {
"meta": {
"count": 132,
"start": 0,
"type": "resource-list"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 3.6720000000000002,
"type": "currency",
"symbol": "AED=X"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 65.075000000000003,
"type": "currency",
"symbol": "AFN=X"
}
}
},
{
.............
}
............
我试过这样但得到例外:
JSONObject mainObj = null;
try {
mainObj = new JSONObject(JSON);
JSONObject getSth = mainObj.getJSONObject("list");
if(mainObj != null){
JSONArray list = getSth.getJSONArray("resources");
if(list != null){
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),""+e.toString(),Toast.LENGTH_LONG).show();
}
我得到了例外:字段中没有值......
请给出一些建议,将这些值存储在(行字段)名称,奖品,符号和类型的数据库表(matrotable)中,我可以尝试通过制作字符串数组并检索和存储sqlite的值,是否有任何其他简单选择...... 感谢
答案 0 :(得分:2)
您的fields
个对象位于resource
对象内,所以
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("resource")
.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
"resources": [ // resources list { // object i "resource": { // fields are inside "resource" object "classname": "Quote", "fields": { "date": "2017-03-16", "price": 3.6720000000000002, "type": "currency", "symbol": "AED=X" } } }
答案 1 :(得分:1)
您缺少resource
JOSNObject解析...
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
JSONObject resource = elem.getJSONObject("resource");
if(resource != null){
JSONObject prods = resource.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
答案 2 :(得分:0)
我建议您使用最简单,最简单的方法来解析json响应以避免此类问题:
1-使用此工具生成模型类:http://www.jsonschema2pojo.org/下载并将生成的类添加到模型包中。
2-将此依赖项添加到您的gradle文件中:
compile 'com.google.code.gson:gson:2.4'
3-调用此方法来解析您的回复:
Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson(json, ResponseModel.class);