【问题标题】:How to Pretty-Print , JSON raw datas on Android [duplicate]如何在 Android 上打印漂亮的 JSON 原始数据 [重复]
【发布时间】:2016-10-09 02:21:00
【问题描述】:

我有一个 JSON 格式的 API,我的 json 数据在我的 android 应用程序上显示为原始数据,我希望它们以像这样的漂亮打印格式显示

不是这样的

这是我的java代码:

package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
@Override


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


findViewById(R.id.my_button).setOnClickListener(this);
}


@Override


public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);


b.setClickable(false);
new LongRunningGetIO().execute();
}

private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws    IllegalStateException, IOException {
InputStream in = entity.getContent();


StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n =  in.read(b);


if (n>0) out.append(new String(b, 0, n));
}


return out.toString();
}


@Override


protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://10.0.2.2:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);


HttpEntity entity = response.getEntity();


text = getASCIIContentFromEntity(entity);


} catch (Exception e) {
return e.getLocalizedMessage();
}


return text;
}


protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);


et.setText(results);


}


Button b = (Button)findViewById(R.id.my_button);


b.setClickable(true);
}


}
}

怎么做?

谢谢

【问题讨论】:

标签: java android json api pretty-print


【解决方案1】:

您需要使用 JSON 库(如 Jackson 或 GS​​ON)才能漂亮地打印输出。有关 Jackson 的示例,请查看答案here

【讨论】:

  • 如果他具体问起杰克逊,我会这样做,但问题并不具体。
猜你喜欢
  • 2017-05-01
  • 2012-12-30
  • 2014-05-19
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2011-10-29
相关资源
最近更新 更多