【问题标题】:Retrieve data using Gson使用 Gson 检索数据
【发布时间】:2013-11-20 18:01:51
【问题描述】:

我已将我的代码粘贴在下面,如果有人能帮助我完成它,我将不胜感激。当我运行我的活动时,我的应用程序内应该会更新一个列表。虽然我无法提取任何数据。当我登录 first 时,我得到 [] 而没有别的。如果我检查它的大小,它会返回为 0

*我希望检索 id、名称和大小并将它们放在列表视图中的文本视图中。

当我从浏览器访问我的 URL 字符串时,我得到了这个:

{ "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;
}

}

activities/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;
        }
    }

【问题讨论】:

  • 你实际上并没有给我们 Main.java 的类定义。
  • 你能说清楚你的期望和得到什么吗?
  • 我已经更新了我的问题。如果您还需要更多信息,请告诉我。

标签: java android parsing gson


【解决方案1】:

在我看来,您正试图以一种过于复杂的方式使用 Gson。

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

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

{ "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 对象的一种自然方法是使用两个类:

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

public class Main {
    String id;
    String name;
}

(请随意将“TopLevel”重命名为更好的名称,无论它在您的应用程序中代表什么。)

现在,将 JSON 解析为 Java 对象(一个 TopLevel 对象,总共包含 4 个 Main 对象),如下所示:

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

【讨论】:

  • 我的回答并没有试图为 OP 的models/Main.java 提供最小的修复,但坦率地说,我越看那个代码,我认为它应该被扔掉的越多。首先学习使用 Gson 将 JSON 解析为 Java 对象的基础知识,然后您将通过很多更简单的东西实现您想要的。
  • 嗯,JsonObject 和 JsonParser Gson 库的一部分。例如,您可以在编写自定义类型适配器时使用它们。无论如何,在这种情况下,Pojo 方法更快
  • 正确,但 JSONObjectJSONParser 不是(注意大写)。看起来 OP 确实混淆了 Android 内置 json.org 的部分内容。导入确实包括org.json.JSONException。另外,我想他没有尝试编译该代码...
  • 是的,你是对的。我也做了同样的假设。例如,他将 JsonParser 分配给 JSONParse。
猜你喜欢
  • 1970-01-01
  • 2017-01-01
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
相关资源
最近更新 更多