无法在Android应用中的Object内返回JSON对象

所以我有一个我正在研究的Android应用程序,它对服务器进行API调用并返回JSON信息。 现在在我的Android应用程序中,我可以解析JSON,但直到第一个数组。 之后它说该类别不存在。

这是JSON响应布局:

[ { "success": 0, "error": "string", "response": { "lastseen": 0, "mapstats": { "maps": [ { "tier": 0, "modeid": 0, "modename": "string", "modecolor": "string", "bonus": 0, "name": "string", "rank": 0, "time": "string", "num_completed": 0 } ], "highest_tier": 0, "num_beaten": 0, "percent_completion": 0 }, "tag_color": "string", "name": "string", "rank": 0, "avatar": "string", "tag": "string", "playtime": 0, "percent": 0 } } ] 

这是我的java类:

 package com.horizonservers.horizon; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.jar.Attributes; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; /https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* A simple {@link Fragment} subclass. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* Activities that contain this fragment must implement the https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* {@link MainFragment.OnFragmentInteractionListener} interface https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* to handle interaction events. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* Use the {@link MainFragment#newInstance} factory method to https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* create an instance of this fragment. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*/ public class MainFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, eg ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private static final Pattern delimeter = Pattern.compile(",\\s+"); private TextView mResult; private OnFragmentInteractionListener mListener; public MainFragment() { // Required empty public constructor } /https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* Use this factory method to create a new instance of https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* this fragment using the provided parameters. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* @param param1 Parameter 1. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* @param param2 Parameter 2. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* @return A new instance of fragment MainFragment. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*/ // TODO: Rename and change types and number of parameters public static MainFragment newInstance(String param1, String param2) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } new PostDataTask().execute("https://www.horizonservers.net/api/v1/PlayerInfo"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_main, container, false); mResult = (TextView) v.findViewById(R.id.tv_result); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* This interface must be implemented by activities that contain this https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* fragment to allow an interaction in this fragment to be communicated https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* to the activity and potentially other fragments contained in that https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* activity. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* 

https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* See the Android Training lesson Communicating with Other Fragments for more information. https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*/ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } class PostDataTask extends AsyncTask { ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { try { return postData(params[0]); } catch (IOException ex) { return "Network error !"; } catch (JSONException ex) { return "Data Invalid !"; } } @Override protected void onPostExecute(String result) { try { JSONObject jsonObject = new JSONObject(result); String NameInfo = jsonObject.getString("name"); JSONObject jsonObject1 = new JSONObject(NameInfo); for(int i = 0; i < jsonObject1.length(); i++){ JSONObject jsonPart = new JSONObject(); //Log.i("response", jsonPart.getString("response")); String newName = jsonPart.getString("name"); //mResult.setText(NameInfo); mResult.setText(newName); } } catch (JSONException e) { mResult.setText("Error!"); } super.onPostExecute(result); if (progressDialog != null) { progressDialog.dismiss(); } } private String postData(String urlPath) throws IOException, JSONException { StringBuilder result = new StringBuilder(); BufferedWriter bufferedWriter = null; BufferedReader bufferedReader = null; try { //Create data to send to server JSONObject dataToSend = new JSONObject(); dataToSend.put("apikey", "UPj07lqWdetOWrk9M8Ya9UZzeIAizjr4sYQRKzkHFYm1KaQDopytCFq9HHCerwNy"); dataToSend.put("steamid", "STEAM_0:1:90345825"); dataToSend.put("maptype", "surf"); //Initialize and config request, then connect to server. URL url = new URL(urlPath); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* milliseconds https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*/); urlConnection.setConnectTimeout(10000 /https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/* milliseconds https://stackoverflow.com/questions/37848383/unable-to-return-json-object-within-object-in-android-app/*/); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); //enable output (body data) urlConnection.setRequestProperty("Content-Type", "application/json");// set header urlConnection.connect(); //Write data into server OutputStream outputStream = urlConnection.getOutputStream(); bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); bufferedWriter.write(dataToSend.toString()); bufferedWriter.flush(); //Read data response from server InputStream inputStream = urlConnection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append("&"); } } finally { if (bufferedReader != null) { bufferedReader.close(); } if (bufferedWriter != null) { bufferedWriter.close(); } } return result.toString(); } }

}

将信息打印到屏幕的具体部分是

  @Override protected void onPostExecute(String result) { try { JSONObject jsonObject = new JSONObject(result); String NameInfo = jsonObject.getString("name"); JSONObject jsonObject1 = new JSONObject(NameInfo); for(int i = 0; i < jsonObject1.length(); i++){ JSONObject jsonPart = new JSONObject(); //Log.i("response", jsonPart.getString("response")); String newName = jsonPart.getString("name"); //mResult.setText(NameInfo); mResult.setText(newName); } } catch (JSONException e) { mResult.setText("Error!"); } super.onPostExecute(result); if (progressDialog != null) { progressDialog.dismiss(); } } 

如何从数组/对象中解析这些对象。 我已经尝试将其转换为数组,但此时它变得更糟。 预先感谢您的帮助。

我不确定您试图提取的JSON响应中的哪些数据。 但我认为使用Google Translate API的这个示例可以帮助您。

JSON响应:

 "data": { "translations": [ { "translatedText": "Hallo Welt", "detectedSourceLanguage": "en" } ] } 

如果我想获得翻译的文本“Hallo Welt”,我会这样做:

 public String parseJSONForTranslation(String jsonString) { try { JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue(); return object.getJSONObject("data").getJSONArray("translations"). getJSONObject(0).getString("translatedText"); } catch (JSONException e) { return null; } } 

正如您所看到的,如果您想通过进入JSON响应的下一个“级别”来进一步提取信息,则可以使用getJSONObject或getJSONArray(取决于它是否为数组),直到达到“级别”为止要提取的数据是。 并且当你处于最后的“级别”时,你只使用getString。 希望这可以帮助你。

您可以在创建JSON对象失败时创建JSON数组

 try { JSONObject jsonObject = new JSONObject(result); // do something }catch (JSONException e) { try{ JSONObject jsonObject = new JSONArray(result); // do something }catch(JSONException e){ //... } } 

我自己没有亲自测试过,但我认为这样的事情应该有效。

JSON中的根元素是一个数组,所以我们将从那里开始。

  public String parseJSONForTranslation(String json) throws JSONException { JSONArray array = new JSONArray(json); // We have an array, so we can loop through each inner object. for (int i = 0; i < array.length(); i++) { // Grab an object from the array so we can get the individual data JSONObject object = array.getJSONObject(i); // Variables that match the same key from your JSON int success = object.getInt("success"); String error = object.getString("error"); JSONObject response = object.getJSONObject("response"); int lastSeen = response.getInt("lastseen"); String tagColor = response.getString("tag_color"); String name = response.getString("name"); int rank = response.getInt("rank"); String avatar = response.getString("avatar"); String tag = response.getString("tag"); int playTime = response.getInt("playtime"); int percent = response.getInt("percent"); JSONObject mapstats = response.getJSONObject("mapstats"); int highestTier = mapstats.getInt("highest_tier"); int numBeaten = mapstats.getInt("num_beaten"); int percentCompletion = mapstats.getInt("percent_completion"); JSONArray maps = mapstats.getJSONArray("maps"); for (int i = 0; i < maps.length(); i++) { JSONObject map = maps.getJSONObject(i); int tier = map.getInt("tier"); int modeId = map.getInt("modeid"); String modeName = map.getString("mode_name"); String modeColor = map.getString("mode_color"); int bonus map.getInt("bonus"); String name = map.getString("name"); int rank = map.getInt("rank"); String time = map.getString("time"); int numCompleted = map.getInt("num_completed"); } } }