如何在Android上进行漂亮打印,JSON原始数据

时间:2016-06-08 17:13:17

标签: java android json api pretty-print

我有一个JSON API,我的json数据在我的Android应用程序上显示为raw,我希望它们以漂亮的打印格式显示,如下所示

Pretty JSON Data

不喜欢这个

JSON Raw display on 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);
}


}
}

怎么做?

由于

1 个答案:

答案 0 :(得分:2)

您需要使用像Jackson或GSON这样的JSON库才能打印输出。以杰克逊为例,看一下答案here