使用GSON fromJson方法将JSON数组转换为对象

frebpwbc  于 2022-11-06  发布在  其他
关注(0)|答案(4)|浏览(215)

我有一个WCFWebservice,其中发送了一个数据模型,我通过JSon(通过实体框架)在Android中获得了这个数据模型,无论如何,我都可以通过此代码成功地获得JSON,并将所有JSON对象存储在AsyncTas类的JSONArray中,以及:

  1. public class Consume extends AsyncTask<Void, Void, Void> {
  2. InputStream inputStream = null;
  3. String result = "";
  4. private ArrayList<Contact> contacts = new ArrayList<Contact>();
  5. @Override
  6. protected Void doInBackground(Void... params) {
  7. String URL = "http://x.x.x.x/MyWCF/Service1.svc/rest/getContact";
  8. ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
  9. try {
  10. HttpClient httpClient = new DefaultHttpClient();
  11. HttpPost post = new HttpPost(URL);
  12. post.setEntity(new UrlEncodedFormEntity(param));
  13. HttpResponse httpResponse = httpClient.execute(post);
  14. HttpEntity httpEntity = httpResponse.getEntity();
  15. //post.setHeader("content-type", "application/json");
  16. inputStream = httpEntity.getContent();
  17. } catch (UnsupportedEncodingException e1) {
  18. Log.e("UnsupportedEncoding", e1.toString());
  19. e1.printStackTrace();
  20. } catch (ClientProtocolException e2) {
  21. Log.e("ClientProtocolException", e2.toString());
  22. e2.printStackTrace();
  23. } catch (IllegalStateException e3) {
  24. Log.e("IllegalStateException", e3.toString());
  25. e3.printStackTrace();
  26. } catch (IOException e4) {
  27. Log.e("IOException", e4.toString());
  28. e4.printStackTrace();
  29. }
  30. try {
  31. BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
  32. StringBuilder sBuilder = new StringBuilder();
  33. String line = null;
  34. while ((line = bReader.readLine()) != null) {
  35. sBuilder.append(line + "\n");
  36. }
  37. inputStream.close();
  38. result = sBuilder.toString();
  39. } catch (Exception e) {
  40. Log.e("StringBuilding", "Error converting result " + e.toString());
  41. }
  42. return null;
  43. }
  44. @Override
  45. protected void onPostExecute(Void aVoid) {
  46. super.onPostExecute(aVoid);
  47. try {
  48. JSONObject object = new JSONObject(result);
  49. JSONArray jArray = object.getJSONArray("getContactResult"); //here i create the JsonArray of all JsonObjects
  50. //Here is the solutions, We make a list of out Contact and make it as down
  51. List<Contact> contacts;
  52. Type listType = new TypeToken<List<Contact>>() {
  53. }.getType();
  54. contacts= new Gson().fromJson(String.valueOf(jArray), listType);
  55. //And here solution is ended !
  56. } catch (JSONException e) {
  57. e.printStackTrace();
  58. }
  59. }

我在android中创建了一个联系人class,代码如下:

  1. public class Contact {
  2. @SerializedName("name")
  3. private String name;
  4. @SerializedName("lastName")
  5. private String lastName;
  6. @SerializedName("phoneNumber")
  7. private String phoneNumber;
  8. @SerializedName("latitude")
  9. private String latitude;
  10. @SerializedName("longitude")
  11. private String longitude;
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setLastName(String lastName) {
  19. this.lastName = lastName;
  20. }
  21. public String getLastName() {
  22. return lastName;
  23. }
  24. public void setPhoneNumber(String phoneNumber) {
  25. this.phoneNumber = phoneNumber;
  26. }
  27. public String getPhoneNumber() {
  28. return phoneNumber;
  29. }
  30. public void setLatitude(String latitude) {
  31. this.latitude = latitude;
  32. }
  33. public String getLatitude() {
  34. return latitude;
  35. }
  36. public void setLongitude(String longitude) {
  37. this.longitude = longitude;
  38. }
  39. public String getLongitude() {
  40. return longitude;
  41. }
  42. }

我用老方法解析这个JSONArray!用这个方法:

  1. ArrayList<Contact> setFields(JSONArray jsonArray) {
  2. ArrayList<Contact> contacts = new ArrayList<Contact>();
  3. for(int i=0; i<jsonArray.length(); i++) {
  4. try {
  5. Contact contact = new Contact();
  6. JSONObject object = (JSONObject) jsonArray.get(i);
  7. contact.setName(object.getString("name"));
  8. contact.setLastName(object.getString("lastName"));
  9. contact.setPhoneNumber(object.getString("phoneNumber"));
  10. contact.setLatitude(object.getString("latitude"));
  11. contact.setLongitude(object.getString("longitude"));
  12. contacts.add(contact);
  13. } catch (JSONException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. return contacts;
  18. }

它工作,但我不想处理和解析JSONArray的这种老方法,并希望使用GSON代替,任何人都可以帮助我与这个例子?这里是我的JSONArrayJSON对象:

  1. {
  2. "getContactResult": [
  3. {
  4. "id": 2041,
  5. "lastName": "xxxx",
  6. "latitude": xxx,
  7. "longitude": xxx,
  8. "name": "xxxx",
  9. "phoneNumber": "xxxx"
  10. }
  11. ]
  12. }

谢谢

7xzttuei

7xzttuei1#

  1. import com.google.gson.reflect.TypeToken;
  2. import java.lang.reflect.Type;
  3. List<Contact> contacts;
  4. Type listType = new TypeToken<List<Contact>>() {
  5. }.getType();
  6. contacts= new Gson().fromJson(jsonArray, listType);

确保您的模型类与json参数和数据类型具有相同的名称。它会将jsonarray解析为java的类型List

qlzsbp2j

qlzsbp2j2#

这已经回答了,但我想分享一件事给你。简单和最好的方法
有一个插件Gson为android工作室。你需要安装。然后去CTRL +插入。你可以创建gson文件。输入一些名称为java文件。
点击该文件,然后粘贴json数据。点击确定。你可以看到你创建的json到gson格式。
谢谢,希望这对你有帮助。

xdnvmnnf

xdnvmnnf3#

Kotlin溶液

  1. import com.google.gson.reflect.TypeToken;
  2. import java.lang.reflect.Type;
  3. val gson = Gson()
  4. val type = object : TypeToken<List<Contact>>() {}.type
  5. val listContact : KycProperties = gson.fromJson(jArray.toString(), type) as Contact

Java解决方案

  1. import com.google.gson.reflect.TypeToken;
  2. import java.lang.reflect.Type;
  3. List<Contact> listContact;
  4. Type type = new TypeToken<List<Contact>>() {
  5. }.getType();
  6. listContact= new Gson().fromJson(jsonArray.toString(), type);
展开查看全部
5us2dqdw

5us2dqdw4#

将Gson和JSON结合起来(一种不同的方法),对于新手来说很简单。

  1. ArrayList<Sukh>sukhs new ArrayList<>();
  2. Gson gson = new Gson();
  3. try {
  4. JSONArray jsonArray = new JSONArray(fullJsonArrayString);
  5. for (int i = 0; i < jsonArray.length(); i++) {
  6. JSONObject jsonObject=jsonArray.getJSONObject(i);
  7. Sukh sukhObject = gson.fromJson(jsonObject.toString(), Sukh.class);
  8. sukhs.add(sukhObject);
  9. }
  10. } catch (JSONException e) {
  11. e.printStackTrace();
  12. }

相关问题