在 Android 中为 Json Post 使用 Gson

Using Gson For Json Post in Android

按照我没有完全理解的教程,我做了以下操作:

我创建了四个 classes。

        package com.example.android.wearable.watchface;
        import com.google.gson.annotations.SerializedName;
        import java.util.ArrayList;

        public class Beansubject {

            @SerializedName("subject")
            private static String subject;
            @SerializedName("price")
            private static String price;
            @SerializedName("author")
            private static String author;
            @SerializedName("topics")
            private static ArrayList<BeanTopic> beanTopics;

            public Beansubject(ArrayList<BeanTopic> beanTopics, String subject, String price, String author) {
                this.beanTopics = beanTopics;
                this.subject = subject;
                this.price = price;
                this.author = author;
            }

            public static String getSubject() {
                return subject;
            }
            public static void setSubject(String subj) {
               subject = subj;
            }
            public static String getPrice() {
                return price;
            }
            public static void setPrice(String pric) {
                price = pric;
            }
            public String getAuthor() {
                return author;
            }
            public static void setAuthor(String aue) {
            author = aue;
            }
            public static ArrayList<BeanTopic> getBeanTopics() {
                return beanTopics;
            }
            public static void setBeanTopics(ArrayList<BeanTopic> beantcs) {
                beanTopics = beantcs;
            }
        }

下一个

            package com.example.android.wearable.watchface;
            import com.google.gson.annotations.SerializedName;
            public class BeanTopic {

                @SerializedName("title")
                private String title;

                public BeanTopic(String title) {
                    this.title = title;
                }

                public String getTitle() {
                    return title;
                }
                public void setTitle(String title) {
                    this.title = title;
                }
            }

下一个

        package com.example.android.wearable.watchface;
        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.StatusLine;
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.Reader;
        public class API {
            private static Reader reader=null;
            public static Reader getData(String SERVER_URL) {
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(SERVER_URL);
                    HttpResponse response = httpClient.execute(httpPost);
                    StatusLine statusLine = response.getStatusLine();
                    if (statusLine.getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        InputStream content = entity.getContent();
                        reader = new InputStreamReader(content);
                    } else {
        //   Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return reader;
            }
        }

终于

    package com.example.android.wearable.watchface;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.TextView;

    import com.google.gson.GsonBuilder;

    import java.io.Reader;
    import java.util.ArrayList;


    public class MainActivity extends Activity {


        ProgressDialog progressDialog;
        TextView txtSubject;
        TextView txtAuthor;
        TextView txtPrice;
        TextView txtTopicsList;
        Beansubject beanSubject;
        StringBuffer topicList;

        public void Json() {

            new AsyncTask<Void,Void,Void>(){
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                    progressDialog.setCancelable(false);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
                @Override
                protected Void doInBackground(Void... voids) {
                    Reader reader=API.getData("http://beta.json-generator.com/api/json/get/OkS85Le");
                    beanSubject = new GsonBuilder().create().fromJson(reader, Beansubject.class);
                    Log.e("Subject: ", beanSubject.getSubject() + "");
                    Log.e("Author: ", beanSubject.getAuthor() + "");
                    Log.e("Price: ", beanSubject.getPrice() + "");
                    ArrayList<BeanTopic> topicArrayList = beanSubject.getBeanTopics();
                    topicList = new StringBuffer();
                    for(BeanTopic topic: topicArrayList){
                        Log.e("topic title: ",topic.getTitle()+"");
                        topicList.append("* " + topic.getTitle()+"\n");
                    }
                    return null;
                }
                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    progressDialog.dismiss();
                    txtSubject.setText("Subject: " + beanSubject.getSubject());
                    txtPrice.setText("price: "+beanSubject.getPrice());
                    txtAuthor.setText("Author: "+beanSubject.getAuthor());
                    txtTopicsList.setText("Topics: "+"\n" + topicList);
                }
            }.execute();

        }

    }

错误是我不确定如何创建 activity class 最后一部分教程中的对象。 对于我在教程的最后一部分中不理解的部分,其中正在创建的对象可能是 linked 而可能不是其他 classes 我随机猜测它们是什么。 我什至在其他 class 中将一些东西设为静态,并删除了 "this." 以使某些东西起作用。请帮助我理解本教程的最后一部分,以便我可以完全理解如何完成这个简单的任务。谢谢。

这是这个简单教程的link: http://www.nkdroid.com/2014/11/json-object-parsing-using-url-in-android.html

好的,这些是我的未知变量:MyActivity.this、progressdialog、txtpostlist、postlist、beanpostarraylist。我现在使用不同的教程 -> 更基础。所以我不确定为什么教程对创建 MainActivity Class 如此含糊。什么不见​​了? http://nkdroid.com/2014/11/json-parsing-using-gson-in-android.html

您需要创建一个布局,其中包含一些具有相应 ID 的 TextView 组件。因此,创建一个 xml 文件,其中包含一些具有正确 ID 的文本视图。然后重写onCreate方法,调用JSON方法:

@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.id.my_layout);
    txtSubject = (TextView) findViewById(R.id.txtSubject);
    ...
    Json();
}

如果有什么不清楚的地方,我建议你阅读基本的 android 教程(官方网站的教程很棒)。

可能有助于查看 API 调用提供的数据。

将结果粘贴到 http://json.parser.online.fr/

curl -v http://beta.json-generator.com/api/json/get/OkS85Le

{"topics": [{"title": "how to add fontawesome icons in android example"},
            {"title": "how to parse json parsing using gson library"},
            {"title": "how to store arraylist in sharedpreferences"}],
 "auther": "nirav kalola",
 "price": "free",
 "subject": "Android Application Development Tutorial"}

因此,JSON 中的 3 个 "title" 元素在 UI 中结束,原因如下:

beanSubject = new GsonBuilder().create().fromJson(reader, Beansubject.class);

ArrayList<BeanTopic> topicArrayList = beanSubject.getBeanTopics();

for(BeanTopic topic: topicArrayList){
                    topicList.append("* " + topic.getTitle()+"\n");
                }

txtTopicsList.setText("Topics: "+"\n" + topicList);

代码获取数据

MVC model/collection 从 JSON 数组创建的对象

UI 集合对象中的列表集

see here 有关适配器从集合对象持有者获取数据的更多信息。