从Gson读取json(string)android

时间:2017-07-25 09:59:00

标签: android json listview

我的json文件

{"VisitorsList":[{"VisitorID":"09005451","VisitorName":" xxxx","VisitorPhon":"","VisitorAddr":"xxxx","GeoCode":"","AutoKey":1},{"VisitorID":"09005468","VisitorName":"xxxxxx","VisitorPhon":"09005468","VisitorAddr":"xxxx","GeoCode":"","AutoKey":2}]}

我想阅读并将此文件中的信息显示给ListView

我的VisitorsListActivity是:

public class VisitorsListActivity extends AppCompatActivity {

public ListView lstVisitors;
static VisitorsList visitorsList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.visitor_list);

    try {

        //********************************** COMELETE THIS SECTION *********************************************

        new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {

            @Override
            public void processFinish(String output) {
                try {
                    if (output == null) output = "";
                    if (output.equals("")) {
                        Toast.makeText(getApplicationContext(),
                                "No Visitor Founded",
                                Toast.LENGTH_LONG)
                                .show();
                        return;
                    }
                    //960105--------------------
                    else if (output.equals("401")) {
                        Toast.makeText(getApplicationContext(),
                                "Error 401",
                                Toast.LENGTH_LONG)
                                .show();
                        return;
                    }
                    //--------------------------------------

                    Log.i("LOG", "output" + output);
                    Gson gson = new Gson();
                    output = output.substring(1, output.length() - 1);

                    /*Toast.makeText(getApplicationContext(),
                            output,
                            Toast.LENGTH_LONG)
                            .show();*/

                    visitorsList = new VisitorsList();
                    visitorsList = gson.fromJson(output, VisitorsList.class);

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

                    Toast.makeText(getApplicationContext(),
                            "exception",
                            Toast.LENGTH_LONG)
                            .show();
                }
            }
        }).execute("http://192.168.1.162:8014/api/Visitors");


        //************************************ visitor list is null :| *******************************************


        /*if( visitorsList == null) {
            Toast.makeText(getApplicationContext(),
                    "data is nul",
                    Toast.LENGTH_LONG)
                    .show();
        }*/

        AdapterVisitor customAdapter = new AdapterVisitor(this, R.layout.visitor_list, visitorsList.VisitorsList);
        customAdapter.notifyDataSetChanged();
        lstVisitors.setAdapter(customAdapter);

        lstVisitors.requestFocus();

        final ViewGroup layoutClear = (ViewGroup) findViewById(R.id.layoutClear);
        layoutClear.setVisibility(View.GONE);

    } catch (Exception e) {
        e.getMessage();
    }

} }

和VisitorsList:

public class VisitorsList {

public VisitorsList() {}

public ArrayList<Visitors> VisitorsList;}

访问者:

public class Visitors {
public String VisitorID;
public String VisitorName;
public String VisitorPhon;
public String VisitorAddr;
public String GeoCode;
public int AutoKey;}

并且始终由Gson创建的访客列表为空。我不知道也许我的问题是从json读书或者也许是访客班......

jsonhelper:

public class JsonHelper {

public static class GetJsonData extends AsyncTask<String, Void, String> {

    public interface AsyncResponse {

        void processFinish(String output);
    }

    public AsyncResponse delegate = null;


    public GetJsonData(AsyncResponse delegate) {
        this.delegate = delegate;
    }


    @Override
    protected String doInBackground(String... strUrl) {

        String str = strUrl[0];
        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(str);
            urlConn = url.openConnection();
            urlConn.setReadTimeout(300000);
            urlConn.setConnectTimeout(5000);

            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"), 8);

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String tmpJson = stringBuffer.toString().replace("\\", "");

            return tmpJson;
        } catch (Exception ex) {
            ex.getMessage();

            return null;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
    }


    @Override
    protected void onPostExecute(String response) {
        delegate.processFinish(response);
    }
}


public static class SetJsonData extends AsyncTask<String, Void, String> {

    String responseServer;


    public interface AsyncResponse {

        void processFinish(String output);
    }

    public AsyncResponse delegate = null;


    public SetJsonData(AsyncResponse delegate) {
        this.delegate = delegate;
    }


    @Override
    protected String doInBackground(String... param) {
        URL url;
        String response = null;
        try {

            url = new URL(param[0]);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(10000);//950718
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(param[1]);
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response = (String.valueOf(responseCode));
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));//950427
                while ((line = br.readLine()) != null) {
                }

            }
            return response;
        } catch (IOException e1) {
            e1.getMessage();

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

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        try {
            super.onPostExecute(result);
            delegate.processFinish(result);
        } catch (Exception e) {
            e.getMessage();
        }
    }

}}

6 个答案:

答案 0 :(得分:0)

您的访客类缺少注释。 用它来正确转换它: http://www.jsonschema2pojo.org/

答案 1 :(得分:0)

答案 2 :(得分:0)

好在第一次阅读AsyncResponse所以你正在使用异步请求是做什么的? 异步请求不会阻止客户端,因此当响应返回时它会继续执行代码,它将执行回调内部的操作。 但是您要调用customAdapter.notifyDataSetChanged();processFinish()来调用它,或者调用Adapter方法中的processFinish工作。

答案 3 :(得分:0)

public class VisitorsList {

public VisitorsList(){}

public ArrayList VisitorsList = new ArrayList&lt;&gt;();}

应该是这样......缺少初始化。

答案 4 :(得分:0)

VisitorsList类:

public class VisitorsList {


        @SerializedName("VisitorsList")
        public List<VisitorsList> VisitorsList;

        public static class VisitorsList {
            @SerializedName("VisitorID")
            public String VisitorID;
            @SerializedName("VisitorName")
            public String VisitorName;
            @SerializedName("VisitorPhon")
            public String VisitorPhon;
            @SerializedName("VisitorAddr")
            public String VisitorAddr;
            @SerializedName("GeoCode")
            public String GeoCode;
            @SerializedName("AutoKey")
            public int AutoKey;
        }
    }

删除此行

 output = output.substring(1, output.length() - 1);

并获得结果:

 Gson gson = new Gson();
visitorsList=gson.fromJson(output), new TypeToken<VisitorsList>() { }.getType());

答案 5 :(得分:0)

我更改VisitorsListActivity,如下所示。并在调用适配器之前设置一个条件,以确保从json读取信息已经完成,这正常工作:

new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {

        @Override
        public void processFinish(String output) {
            try {
                if (output == null) output = "";
                if (output.equals("")) {
                    Toast.makeText(getApplicationContext(),
                            "No Visitor Founded",
                            Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                else if (output.equals("401")) {
                    Toast.makeText(getApplicationContext(),
                            "Error 401",
                            Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                Log.i("LOG", "output" + output);
                Gson gson = new Gson();
                output = output.substring(1, output.length() - 1);


                try {
                    visitorsList = new VisitorsList();
                    visitorsList = gson.fromJson(output, VisitorsList.class);
                    if(visitorsList != null) {
                        d.cancel();
                        adapter = new AdapterVisitor(visitorsList.VisitorsList);
                        adapter.notifyDataSetChanged();
                        lstVisitors.setAdapter(adapter);

                        lstVisitors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                // ******
                                Object o = lstVisitors.getItemAtPosition(position);
                                Intent i = new Intent(getApplicationContext(),DateSelectorActivity.class);
                                Visitors v = (Visitors) o;
                                i.putExtra("VisitorID", v.VisitorID);
                                startActivity(i);
                            }
                        });
                    }

                }catch (Exception e) {
                    Log.i("LOG", getAssets().toString() + "exception" + e);
                }


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

    }).execute(url);