使用Gson检索数据 [英] Retrieve data using Gson

查看:87
本文介绍了使用Gson检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面粘贴了我的代码,如果有人可以帮助我完成代码,我们将不胜感激.当我运行活动时,应该在我的应用程序内部更新列表.我还无法提取任何数据.当我先登录 时,我得到的是 [] .如果我检查尺寸,它将返回为 0 .

I have pasted my code below and would appreciate it if someone would help me work through it. When I run my activity a list should be getting updated inside of my app. I haven't been able to pull in any data though. When I log first I get [] and nothing else. If I check the size it comes back as 0.

**我希望检索ID,名称和大小,并将它们放在列表视图内的文本视图中.

*I am expecting to retrieve the id, name, and size and place them in textviews within a listview.

当我从浏览器访问URL字符串时,会显示以下信息:

When I access my URL string from my browser I get this:

{ "begin":
   [
    {"id":1,"name":"1","size":2},
    {"id":2,"name":"2","size":2}],
  "end":
   [
    {"id":1,"name":"1","size":2},
    {"id":2,"name":"2","size":2}
   ]
}

models/Main.java

import android.content.Context;

import ...Cement;
import ...utils.NetworkUtilities;
import ...utils.ServerErrorException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class Main {
    private String id;
    private String name;
    private static List<Main> first;
    public Main() {}
    public String getId() {
     return id;
    }
    public String getName() {
     return name;
    }

/**
 * @return array of Main.
 * @throws JSONException
 */
public static List<Main> updateMain(Context context) throws JSONException, ServerErrorException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    if( Member.session(context) != null ) {
        params(new BasicNameValuePair(Cement.ACCESS_CODE, Member.session(context).getAccessCode()));
    } else {
        return null;
    }

    String URL = Cement.BASE_URL + Cement.MAIN_URI;

    String jsonString = NetworkUtilities.SendHttpGet(URL, params);
    if (jsonString == null) return main(context);

    JSONParse parser = new JsonParser();

    JSONObject jsonObject = parser.parse(jsonString).getAsJsonObject();

    if (jsonObject != null && jsonObject.get("begin") != null) {

        Gson gson = new Gson();

        for (JSONElement mainObject : jsonObject.get("begin").getAsJsonArray()) {
            Main spot = gson.fromJson(mainObject.getAsJsonObject().get("begin"), Main.class);
            Main.setSpot(context,spot);
        }

    } else {
      // Server error exception...
    }
    return first(context);
}

public static List<Main> first(Context context) {
    if (first == null) {
        try {
            first = new ArrayList<Main>();
        } finally {
            if (first == null) {
                first = new ArrayList<Main>();
            }
        }
    }
    return first;
}

public static void setMain(Context context, Main second) {
    Main previous = find(context, second.getId());
    if (previous != null) {
        first.set(first.indexOf(previous), second);
    } else {
        first = first(context);
        first.add(second);
    }
}

public static Main find(Context context, String id) {
    for(Main first : first(context)) {
        if(second.getId().equals(id)) {
            return second;
        }
    }
    return null;
}

}

活动/Home.java

public class Home extends Fragment {
    private GetMainListTask mGetMainListTask = null;
    private ListView mMainListView;
    private MainListAdapter mMainListAdapter;
    private List<Main> mFirst;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment, container, false);
        mFirst = First.first(mContext);
        mMainListView = (ListView) rootView.findViewById(R.id.ListView);
        mMainListAdapter = new MainListAdapter();
        mMainListView.setAdapter(mMainListAdapter);
        getFirst(true);
        return rootView;
    }

    public void getFirst(Boolean showProgressDialog){
     if (showProgressDialog) {
      mProgressDialog = ProgressDialog.show(mContext, "", "Loading...", true);
     }
     mGetMainListTask = new GetMainListTask();
     mGetMainListTask.execute();
    }

    public class GetMainListTask extends AsyncTask<Void, Void, List<Main>> {
        private List<Exception> exceptions = new ArrayList<Exception>();

        @Override
        protected List<Main> doInBackground(Void... params) {
            try {
                return Main.updateMain(Home.this.getApplicationContext());
            } catch (ServerErrorException e) {
                exceptions.add(e);
                return null;
            } catch (JSONException e) {
                exceptions.add(e);
                return null;
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(final List<Main> first) {
            for (Exception e : exceptions) {
                // Error...
            }
            if(first == null && exceptions.isEmpty()) {
                if (getApplicationContext() != null) {
                    // Error...
                }
            }
            onGetMainResult(first);
        }
    }

    public void onGetMainResult(List<Main> first) {
        boolean worked = (first != null && first.size() != 0);
        mGetMainListTask = null;
        if (worked) {
            mFirst = first;
            if (mMainListAdapter != null) {
                mMainListAdapter.notifyDataSetChanged();
            }
        }
    }

    public class MainListAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mFirst.size();
        }
        @Override
        public Object getItem(int i) {
            return mFirst.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View convertView, ViewGroup parent) {
            View view = View.inflate(getApplicationContext(), R.layout.list, null);
            final Main first = mFirst.get(i);
            if (mContext != null && first != null) {
                // Do stuff...
            }
            return view;
        }
    }

推荐答案

在我看来,您正在尝试以过于复杂的方式使用Gson.

It looks to me like you are trying to use Gson in a way too complicated way.

(另外,您的代码中的JSONParseJSONObject是什么?显然来自org.json或Jackson.为什么实际上在同一段代码中要使用几个不同的JSON库?请坚持使用Gson!)

(Also, what are JSONParse and JSONObject in your code? From org.json or Jackson apparently. Why on earth would you use several different JSON libraries in the same piece of code? Just stick to Gson!)

如果我们以您的原始JSON字符串开头:

If we begin with your original JSON string:

{ "begin":
   [
    {"id":1,"name":"1","size":2},
    {"id":2,"name":"2","size":2}],
  "end":
   [
    {"id":1,"name":"1","size":2},
    {"id":2,"name":"2","size":2}
   ]
}

使用两个类将其建模为Java对象的自然方法是这样的:

A natural way to model that into Java objects would be something like this, using two classes:

public class TopLevel {
    List<Main> begin;
    List<Main> end;
}

public class Main {
    String id;
    String name;
}

(可以将"TopLevel"重命名为更好的名称,无论您在应用程序中表示什么.)

(Feel free to rename "TopLevel" to something better, to whatever it represents in your application.)

现在,将JSON解析为Java对象(一个TopLevel对象总共包含4个Main对象),就很简单:

Now, parsing the JSON into Java objects (one TopLevel object containing a total of 4 Main objects), is as simple as:

Gson gson = new GsonBuilder().create();
TopLevel topLevel = gson.fromJson(jsonString, TopLevel.class);

这篇关于使用Gson检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆