У меня есть массив JSON, отправленный с моего SQL-сервера через PHP в следующем формате, который мне трудно разобрать без возникновения ошибок.Как разобрать неназванный JSON Array в приложении для Android
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
Я проверял свой JSON на JSONLint, и он подходит как действительный. Я также использовал код журнала для распечатки своего JSON в отладчике приложения Eclipse после того, как мой HTTP-клиент обработал его, и он также отлично работает (он показывает JSON, как указано выше, поэтому я знаю, что он скачал правильно).
Я пытаюсь установить JSON Parser в следующее действие, но все мои попытки до сих пор либо содержали слишком много ошибок для запуска, либо просто не возвращали результатов из-за ошибок синтаксического анализа JSON.
Вот код основного вида деятельности. Код для этой деятельности адаптирован из NewThinkTank.com (Android Development 15), и я пытаюсь настроить его для моих нужд, но структура JSON, используемая в этом примере, очень отличается от моей.
Я надеялся, что кто-то может предложить какой-то код или дать мне несколько указателей относительно того, как я могу правильно разобрать этот массив JSON. Я довольно новичок в программировании на Android, так что это довольно крутая задача, чтобы разобраться в себе.
Спасибо за ваше время.
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";
// Will hold the values I pull from the JSON
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
@Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//this allowed me to verify the JSON download in the debugger
Log.v("JSONParser RESULT ", result);
// JSON parsing needs to happen here...
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Спасибо за ваш ответ. Это то, что я уже пробовал, и проблема, с которой я столкнулась, это «JSONArray array = new JSONArray (result);» бросает «исключение исключенного типа исключения JSON» в Eclipse, поэтому я даже не могу запустить приложение. Это для меня не имеет смысла, потому что все, что я делаю, говорит о том, что «массив» представляет собой новый JSONArray с использованием скомпилированной строки " результат ". Для справки, это то, что я вложил в мою mainactivity, http://pastebin.com/s1TvkCC1 – rtg93
Мне просто нужно было заключить в try и catch цикл, и немного подстройки заставили его работать в конце. Результат не тот, что я хотел (он выводит строки, а мне нужны списки - derp), но код, который вы предоставили, исправил мою проблему, поэтому спасибо за вашу помощь! – rtg93