JSON从URL解析并发布textview

时间:2018-04-21 12:21:35

标签: android json textview

如何为Android Studio解析此json

并且需要在textview

中单独显示每个项目

谢谢大家....

仅限网址内容

{"s":true,"code":0,"errors":[],"c":"2.54","y":"5.8","i":"2.9","x":"0"}

我的某人活动

public class aFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, null);
        super.onCreate(savedInstanceState);
        new TransTask()
                .execute("MYURL");
        return view;
    }
    class TransTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            StringBuilder sb = new StringBuilder();
            try {
                URL url = new URL(params[0]);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(url.openStream()));
                String line = in.readLine();
                while(line!=null){
                    Log.d("HTTP", line);
                    sb.append(line);
                    line = in.readLine();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();
        }
    }
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Log.d("JSON", s);
    parseJSON(s);
}


private void parseJSON(String s) {
    try{
        JSONObject jsonObject = new JSONObject(s);

        String name = jsonObject.getString("s");
        String title = jsonObject.getString("code");
        String tag = jsonObject.getString("errors");
        String info = jsonObject.getString("c");
        String info = jsonObject.getString("y");
        String inf = jsonObject.getString("i");
        String in = jsonObject.getString("x");
    }
    catch(JSONException e) {
        e.printStackTrace();

    }
}

为什么super.onPostExecute(s);无法解析方法'onPostExecute(java.lang.string)'

1 个答案:

答案 0 :(得分:0)

您可以在&#39; onPostExecute&#39;中设置各种小部件的值。 AsyncTask的方法。

使用返回的字符串初始化JSONObject。然后使用getBoolean,getString,getDouble等各种方法作为值。您甚至可以使用getJSONObject和getJSONArray方法获取嵌套的json对象或数组。使用JSONObject将要求您在代码中处理JSONException。

    JSONObject jsonObject = new JSONObject(stringObject);
    boolean s = jsonObject.getBoolean("s");
    int code = jsonObject.getInt("code");
    JSONArray errors = jsonObject.getJSONArray("errors");
    //Similar to above

或者,您也可以使用像GSON这样的库来反序列化您的json。