首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android: Sort JSON

Android: Sort JSON
EN

Stack Overflow用户
提问于 2016-12-21 08:57:17
回答 2查看 98关注 0票数 1

不熟悉使用REST API和JSON文件,但我已经从一个天气API中检索了有关我当前位置的天气条件的数据。JSON文件包含数据,例如我的位置、天气速度等。我希望将所有这些单独的数据部分排序到textViews中,以便可以清楚地看到它们。

我的异步类:

代码语言:javascript
复制
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import java.util.ArrayList;
import android.widget.*;
import java.util.Date;
import android.util.Log;

public class RESTAPI extends Activity {

ArrayList<String> items = new ArrayList<String>();
// json test string
String jsonTest;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restapi);
    // start the  AsyncTask for calling the REST service using httpConnect class
    new AsyncTaskParseJson().execute();
}


// added asynctask class methods below -  you can make this class as a separate class file
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    // set the url of the web service to call
    String yourServiceUrl = "http://api.apixu.com/v1/current.json?key=e87e62510df946cc84c02652162112&q=LN11RX";

    @Override

    protected void onPreExecute() {
    }

    @Override

    protected String doInBackground(String... arg0) {

        try {
            // create new instance of the httpConnect class
            httpConnect jParser = new httpConnect();

            // get json string from service url
            String json = jParser.getJSONFromUrl(yourServiceUrl);

            // save returned json to your test string
            jsonTest = json.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {
        TextView tv1 = (TextView) findViewById(R.id.jsontext);
        tv1.setText(jsonTest);
    }

}

}

我的处理网址的httpConnect类:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;


public class httpConnect {

final String TAG = "JsonParser.java";

static String json = "";

public String getJSONFromUrl(String url) {

    try {

        URL u = new URL(url);
        HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
        restConnection.setRequestMethod("GET");
        restConnection.setRequestProperty("Content-length", "0");
        restConnection.setUseCaches(false);
        restConnection.setAllowUserInteraction(false);
        restConnection.setConnectTimeout(10000);
        restConnection.setReadTimeout(10000);
        restConnection.connect();
        int status = restConnection.getResponseCode();

        // switch statement to catch HTTP 200 and 201 errors
        switch (status) {
            case 200:
            case 201:

                BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));

                // create a new string builder to store json data returned from the REST service
                StringBuilder sb = new StringBuilder();
                String line;

                // loop through returned data line by line and append to stringbuilder 'sb' variable
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();

                try {
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing data " + e.toString());
                }
                return json;
        }
        // HTTP 200 and 201 error handling from switch statement
    } catch (MalformedURLException ex) {
        Log.e(TAG, "Malformed URL ");
    } catch (IOException ex) {
        Log.e(TAG, "IO Exception ");
    }
    return null;
}

那么有没有办法对返回的数据进行排序,并将每一位数据放入它自己的文本框中呢?

JSON截图:

EN

回答 2

Stack Overflow用户

发布于 2016-12-21 12:25:09

如果我正确理解了您的问题,请尝试使用此link。如果我误解了,请让我知道,我会试着用另一种方法来帮助你。

编辑:大致是另一种动态创建新TextView和设置数据的方法:

代码语言:javascript
复制
TextView view;
LinearLayout currLayout = (LinearLayout) findViewById(R.id.LinearLayout);
for(String value : items) {
    view = new TextView();
    view.setText(value);
    currLayout.addView(view);
}
票数 0
EN

Stack Overflow用户

发布于 2016-12-22 15:11:07

  • 为您获得的响应创建pojo类:

像这样打开任何转换站点:-

http://www.jsonschema2pojo.org/

  • 在这里粘贴json响应,然后单击zip,所有的pojo类都将自动为您创建。

现在,在您的代码中执行以下操作

代码语言:javascript
复制
protected String doInBackground(String... arg0) {

        try {
            // create new instance of the httpConnect class
            httpConnect jParser = new httpConnect();

            // get json string from service url
            String json = jParser.getJSONFromUrl(yourServiceUrl);

            // save returned json to your test string
            jsonTest = json.toString();
Gson gson = new Gson();
/*here Example class is the main pojo class, you can use this class which will be there in the zip, which is created from jsontoPojo converting site */

Example  response = gson.fromJson(json, Example.class);

/*
 *Now to get data 
 * just do this */

String name = getLocation().getName();
.
.
.


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

有关详细信息,请查看此示例,example of data parsing using gson

并且您还需要在build.gradle文件中添加此依赖项

代码语言:javascript
复制
compile 'com.google.code.gson:gson:2.4'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41253570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档