Retrieve data using Gson

2019-09-01 03:50发布

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.

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

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

}

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

1条回答
Luminary・发光体
2楼-- · 2019-09-01 04:12

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

(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!)

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}
   ]
}

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

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

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);
查看更多
登录 后发表回答