如何漂亮打印 JSON Android 的原始数据

How to Pretty-Print , JSON raw datas on Android

我在 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);
}


}
}

怎么做?

谢谢

您需要使用像 Jackson 或 GS​​ON 这样的 JSON 库来漂亮地打印您的输出。以 Jackson 为例,请查看答案 here.