我無法從JSONObject中檢索Id並將其傳遞給字符串以記錄該玩家的特定拼圖的Id,但在行上String idString = obj.getString(「 ID」);如何從JSONObject中檢索Id
「我得到org.json.JSONException:Id的無值」
我通過調用這個類檢查玩家的用戶名和密碼的服務器獲取這些信息。
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;
public class GetTodaysPuzzle implements OnRetrieveHttpData {
public String GetTodaysPuzzle(String mUserName, String mPassword)
{
RetrieveHTTPData GetTodayspuzzle = new RetrieveHTTPData(this);
return GetTodayspuzzle.GetResponseData("urlString" + mUserName + "&password=" + mPassword);
}
@Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Server Response", httpData);
}
class GetTodaysPuzzleTask extends AsyncTask<String, String, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
// Get response from server
String json = GetTodaysPuzzle(params[0], params[1]);
// Check if a puzzle was returned
if (json.contains("The request is invalid"))
{
return false;
}
try
{
// Calculate today's date in order to set wordsearch date
Time today = new Time();
today.setToNow();
String formattedDate = Dates.ConvertUStoUK(today.year + "-"
+ (today.month + 1) + "-" + today.monthDay);
// Create wordsearch
WordSearch wordSearch = WordSearch.CreateWordSearch(json,
formattedDate);
if (wordSearch == null)
{
return false;
}
// Save wordsearch to collection
WordSearchDatabase.Add(wordSearch);
// WordSearchDatabase.Save();
return true;
}
catch (Exception e)
{
Log.e("GetTodaysPuzzleTask", e.getMessage());
return false;
}
}
}
}
然後將所有信息存儲到Wordsearch類的JSONArrays中。
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class WordSearch {
public String Id;
public String Date;
public List<Word> Words;
public Letter[] Letters;
public final int NUM_OF_ROWS;
public final int NUM_OF_COLS;
public int Score = -1;
private boolean containsSolution = false;
public boolean canBeSubmitted = true;
private boolean complete = false;
private boolean submitted = false;
public static WordSearch CreateWordSearch(String json, String date)
{
List<Word> listOfWords = new ArrayList<Word>();
List<String> listOfRows = new ArrayList<String>();
try
{
// Create a JSON Object from JSON string
JSONObject obj = new JSONObject(json);
// Get Id
String idString = obj.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = obj.getJSONArray("Words");
JSONArray puzzleArray = obj.getJSONArray("Grid");
// Parse Words array
for (int i = 0; i < wordsArray.length(); i++)
{
String name = wordsArray.getString(i);
Word word = new Word(name);
listOfWords.add(word);
}
// Parse Puzzle
for (int k = 0; k < puzzleArray.length(); k++)
{
String puzzle = puzzleArray.getString(k);
listOfRows.add(puzzle);
}
// Create WordSearch
return new WordSearch(idString, date, listOfWords, listOfRows,
false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
這是我第一次在Android中使用API服務器和JSONObject的,所以任何幫助將不勝感激。謝謝。
現在我明白了,謝謝你的幫助。 – user3047041