我试图从 JSON API 中获取所有价值,我已经设法获得了几乎所有的价值,除了一个!如您所见,这是来自服务器的 JSON 输出。(我不能改变它)
{
"error":"",
"S8tf":{
"infoToken":"wCfhXe",
"deleteToken":"gzHTfGcF",
"size":122484,
"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6",
"filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"
},
"S29N":{
"infoToken":"joRm6p",
"deleteToken":"IL5STLhq",
"size":129332,
"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d",
"filename":"Stockholmsyndromet.docx"
}
}
如您所见,每个字符串/“数组”都以“fileId”开头,这是从服务器随机生成的。我正在使用下面的代码,我可以看到所有值,例如:文件名、大小、sh1 等。但我似乎无法弄清楚如何获取“fileId”。fileId 是(在这个 json 中)S8tf 和 S29N
我的代码:
public class FilesActivity extends SherlockActivity {
private static String TAG_FILENAME = "filename";
private static String TAG_SIZE = "size";
private static String TAG_ITOKEN = "infoToken";
private static String TAG_DTOKEN = "deleteToken";
private static String TAG_SHA1 = "sha1";
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
String response = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://api.bayfiles.net/v1/account/files?session=of1903u3pj43c3can8rc33gc42");
try {
JSONObject json = new JSONObject();
json.put("filename", "error");
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
postMethod.setHeader( "Content-Type", "application/json" );
response = httpClient.execute(postMethod,resonseHandler);
TextView txt = (TextView)findViewById(R.id.nodata);
JSONObject request = new JSONObject(response);
for (Iterator<?> keyIterator = request.keys(); keyIterator.hasNext(); ) {
String key = (String) keyIterator.next();
JSONObject object = request.optJSONObject(key);
ArrayList<fileObject> objectList = new ArrayList<fileObject>();
if (object != null) {
//Setting TAGs
TAG_FILENAME = object.getString("filename");
TAG_SIZE = object.getString("size");
TAG_ITOKEN = object.getString("infoToken");
TAG_DTOKEN = object.getString("deleteToken");
TAG_SHA1 = object.getString("sha1");
txt.setText(
TAG_FILENAME + "\n"
+ TAG_SIZE + "\n"
+ TAG_ITOKEN + "\n"
+ TAG_DTOKEN + "\n"
+ TAG_SHA1 + "\n"
+ txt.getText()
);
Log.d("log_tag", object.getString("filename"));
}
}
}
catch(Exception e)
{
e.printStackTrace();
Log.d("log_tag", "Error: " + e.toString());
}
}
}
如果您没有得到它,我正在尝试从 fileId aka S8tf 和 S29N 中获取值,这些是随机数,由服务器生成。
编辑:谢谢你们!因为我知道发帖人弄明白这很烦人,而你不能,所以我所做的就是把 String fileId = key; 在我的对象循环中,像这样:
if (object != null) {
fileObject obj = new fileObject();
obj.setFileId(key);
obj.setFileName(object.getString("filename"));
obj.setSize(object.getString("size"));
obj.setInfoToken(object.getString("infoToken"));
obj.setDeleteToken(object.getString("deleteToken"));
obj.setSha1(object.getString("sha1"));
objectList.add(obj);
Log.d("fileId", key); // Shows both of the values!
}