我正在尝试在我的应用程序中解析json:
所以首先我为我的安卓应用程序创建了常量类,它有大约6个app.config变量:
(类别: 1)
public class Constants{
// url to make request
public static String url = "http://server.com/";
// JSON Node names
public static final String TAG_CONTACTS = "contacts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_EMAIL = "email";
public static final String TAG_ADDRESS = "address";
public static final String TAG_GENDER = "gender";
}现在我想在不同的类中使用它,所以我继续创建了不同的类:
(类别: 2)
public class ReadFiles{
public void readConstant(){
//appConfig is JSONArray
JSONArray appConfig = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(c.url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject d = details.getJSONObject(i);
// Storing each json item in variable
String id = d.getString(Constants.TAG_ID); //Error:
//ERROR : The method getString(int) in the type JSONArray is not applicable for the arguments-(String)
String name = d.getString(Constants.TAG_NAME);
String email = d.getString(Constants.TAG_EMAIL);
String address = d.getString(Constants.TAG_ADDRESS);
String gender = d.getString(Constants.TAG_GENDER);
} catch (JSONException e) {
e.printStackTrace();
}
}我在block:String name = c.getString(Constants.TAG_NAME);上遇到错误,我试图通过解析json将常量值应用于局部变量。
我遵循了eclipse的技巧,并且也尝试去做
String name = c.(Constants.TAG_NAME);但还是不走运。这个区块出了什么问题?如何将json值赋给局部变量?这就是我想要实现的:android-json-parsing-tutorial,但是我想把常量放在单独的类中。
更新:所以我做了你建议的修改,我得到了新的错误:
String tabTitle = appConfig.(ConfigConstants.TITLE); //Error: Syntax error on token ".", Identifier expected after this token
发布于 2013-03-25 14:26:10
为什么不简单地使用这个呢?
Constants.TAG_NAME为什么要实例化Constants类呢?由于Constants类static中的所有字段,它们只需要以static方式访问(即)通过使用ClassName(Constants).
更新:-
appConfig.(ConfigConstants.TITLE);不是应该有个方法吗?就像这样。
appConfig.someMethodName(ConfigConstants.TITLE);发布于 2013-03-25 14:36:24
我猜您在包中使用的是JSONArray类
org.json.JSONArray它有一个方法
getString(int)如果这个方法接受一个整型参数,如果你传递一个字符串参数,很明显Eclipse会抛出一个错误
https://stackoverflow.com/questions/15608862
复制相似问题