- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我正在开发一个 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;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link MainFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link MainFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MainFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. 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
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MainFragment.
*/
// 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;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
class PostDataTask extends AsyncTask<String, Void, String> {
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 /* milliseconds */);
urlConnection.setConnectTimeout(10000 /* milliseconds */);
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 (取决于它是否是数组),直到到达“level”,您要提取的数据所在的位置。只有当你处于最后一个“级别”时,你才使用 getString 。希望这可以帮助您。
关于java - 无法在 Android 应用程序的对象内返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37848383/
我的一位教授给了我们一些考试练习题,其中一个问题类似于下面(伪代码): a.setColor(blue); b.setColor(red); a = b; b.setColor(purple); b
我似乎经常使用这个测试 if( object && object !== "null" && object !== "undefined" ){ doSomething(); } 在对象上,我
C# Object/object 是值类型还是引用类型? 我检查过它们可以保留引用,但是这个引用不能用于更改对象。 using System; class MyClass { public s
我在通过 AJAX 发送 json 时遇到问题。 var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Wil
当我尝试访问我的 View 中的对象 {{result}} 时(我从 Express js 服务器发送该对象),它只显示 [object][object]有谁知道如何获取 JSON 格式的值吗? 这是
我有不同类型的数据(可能是字符串、整数......)。这是一个简单的例子: public static void main(String[] args) { before("one"); }
嗨,我是 json 和 javascript 的新手。 我在这个网站找到了使用json数据作为表格的方法。 我很好奇为什么当我尝试使用 json 数据作为表时,我得到 [Object,Object]
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我听别人说 null == object 比 object == null check 例如: void m1(Object obj ) { if(null == obj) // Is thi
Match 对象 提供了对正则表达式匹配的只读属性的访问。 说明 Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。所有的
Class 对象 使用 Class 语句创建的对象。提供了对类的各种事件的访问。 说明 不允许显式地将一个变量声明为 Class 类型。在 VBScript 的上下文中,“类对象”一词指的是用
Folder 对象 提供对文件夹所有属性的访问。 说明 以下代码举例说明如何获得 Folder 对象并查看它的属性: Function ShowDateCreated(f
File 对象 提供对文件的所有属性的访问。 说明 以下代码举例说明如何获得一个 File 对象并查看它的属性: Function ShowDateCreated(fil
Drive 对象 提供对磁盘驱动器或网络共享的属性的访问。 说明 以下代码举例说明如何使用 Drive 对象访问驱动器的属性: Function ShowFreeSpac
FileSystemObject 对象 提供对计算机文件系统的访问。 说明 以下代码举例说明如何使用 FileSystemObject 对象返回一个 TextStream 对象,此对象可以被读
我是 javascript OOP 的新手,我认为这是一个相对基本的问题,但我无法通过搜索网络找到任何帮助。我是否遗漏了什么,或者我只是以错误的方式解决了这个问题? 这是我的示例代码: functio
我可以很容易地创造出很多不同的对象。例如像这样: var myObject = { myFunction: function () { return ""; } };
function Person(fname, lname) { this.fname = fname, this.lname = lname, this.getName = function()
任何人都可以向我解释为什么下面的代码给出 (object, Object) 吗? (console.log(dope) 给出了它应该的内容,但在 JSON.stringify 和 JSON.parse
我正在尝试完成散点图 exercise来自免费代码营。然而,我现在只自己学习了 d3 几个小时,在遵循 lynda.com 的教程后,我一直在尝试确定如何在工具提示中显示特定数据。 This code
我是一名优秀的程序员,十分优秀!