使用GSON的fromJson方法将JSONArray转换为对象

5

我有一个 WCF Webservice,其中发送一个数据模型,Android 通过 JSon(使用实体框架)获取该模型。无论如何,我可以通过此代码成功获取该 JSON 并将所有 JSON 对象存储在 AsyncTas 类的 JSONArray 中,在:

public class Consume extends AsyncTask<Void, Void, Void> {

            InputStream inputStream = null;
            String result = "";
            private ArrayList<Contact> contacts = new ArrayList<Contact>();

        @Override
            protected Void doInBackground(Void... params) {
                String URL = "http://x.x.x.x/MyWCF/Service1.svc/rest/getContact";
                ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost post = new HttpPost(URL);
                    post.setEntity(new UrlEncodedFormEntity(param));
                    HttpResponse httpResponse = httpClient.execute(post);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    //post.setHeader("content-type", "application/json");
                    inputStream = httpEntity.getContent();

                } catch (UnsupportedEncodingException e1) {
                    Log.e("UnsupportedEncoding", e1.toString());
                    e1.printStackTrace();
                } catch (ClientProtocolException e2) {
                    Log.e("ClientProtocolException", e2.toString());
                    e2.printStackTrace();
                } catch (IllegalStateException e3) {
                    Log.e("IllegalStateException", e3.toString());
                    e3.printStackTrace();
                } catch (IOException e4) {
                    Log.e("IOException", e4.toString());
                    e4.printStackTrace();
                }
                try {
                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

                    StringBuilder sBuilder = new StringBuilder();

                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sBuilder.append(line + "\n");
                    }
                    inputStream.close();
                    result = sBuilder.toString();
                } catch (Exception e) {
                    Log.e("StringBuilding", "Error converting result " + e.toString());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                try {
                    JSONObject object = new JSONObject(result);
                    JSONArray jArray = object.getJSONArray("getContactResult");  //here i create the JsonArray of all JsonObjects

//Here  is the solutions, We make a list of out Contact and make it as down

            List<Contact> contacts;
           Type listType = new TypeToken<List<Contact>>() {
           }.getType();
           contacts= new Gson().fromJson(String.valueOf(jArray), listType);

//And here solution is ended !

               } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

我在Android中创建了一个联系人class,以下是代码:

    public class Contact {


 @SerializedName("name")
    private String name;

        @SerializedName("lastName")
        private String lastName;

        @SerializedName("phoneNumber")
        private String phoneNumber;

        @SerializedName("latitude")
        private String latitude;

        @SerializedName("longitude")
        private String longitude;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setPhoneNumber(String phoneNumber) {
            this.phoneNumber = phoneNumber;
        }

        public String getPhoneNumber() {
            return phoneNumber;
        }

        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }

        public String getLatitude() {
            return latitude;
        }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLongitude() {
        return longitude;
    }
}

我用旧的方法解析这个JSONArray!通过以下方法:

     ArrayList<Contact> setFields(JSONArray jsonArray) {
        ArrayList<Contact> contacts = new ArrayList<Contact>();
            for(int i=0; i<jsonArray.length(); i++) {
                try {
                    Contact contact = new Contact();
                    JSONObject object = (JSONObject) jsonArray.get(i);
                    contact.setName(object.getString("name"));
                    contact.setLastName(object.getString("lastName"));
                    contact.setPhoneNumber(object.getString("phoneNumber"));
                    contact.setLatitude(object.getString("latitude"));
                    contact.setLongitude(object.getString("longitude"));
                    contacts.add(contact);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return contacts;
        }

它能够工作,但我不想用旧的方法处理和解析JSONArray,而想使用GSON。有谁能帮我提供这个示例? 这是我的JSONArrayJSON对象:

    {
  "getContactResult": [
    {
      "id": 2041,
      "lastName": "xxxx",
      "latitude": xxx,
      "longitude": xxx,
      "name": "xxxx",
      "phoneNumber": "xxxx"
    }
  ]
}

谢谢


Gson文档哪里不清楚?另外,也许你应该研究一下使用Gson转换器的Retrofit。 - OneCricketeer
您可以尝试使用链接 - asdcvf
4个回答

20
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

List<Contact> contacts;    
Type listType = new TypeToken<List<Contact>>() {
                    }.getType();
 contacts= new Gson().fromJson(jsonArray, listType);

这应该可以工作。请确保您的模型类与json参数名称和数据类型相同。它将把json数组解析为java的List类型


谢谢,朋友。在你说之前我已经完成了,但还是谢谢你的建议。在Gson方法中,jsonArray应该作为字符串传递,所以应该是:String.valueOf(jArray)。并且我将我的联系人字段SerializedName进行了编辑。在这里,你可以看到编辑后的效果。 - Alireza
1
最近出现了这个问题,它正是我所需要的。谢谢! - Kyon147

2

这个问题已经有答案了,但我想和你分享一件事。有一个适用于Android Studio的插件Gson。你需要安装它,然后按CTRL + insert键。你可以创建gson文件,输入一些Java文件的名称。

点击该文件,然后粘贴您的json数据。点击确定。您可以看到您创建的json格式转换为gson格式。

谢谢,希望这能帮助到你。


1
Kotlin解决方案
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

val gson = Gson()
val type = object : TypeToken<List<Contact>>() {}.type
val listContact : KycProperties = gson.fromJson(jArray.toString(), type) as Contact

Java解决方案
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

List<Contact> listContact;    
Type type = new TypeToken<List<Contact>>() {
                }.getType();
listContact= new Gson().fromJson(jsonArray.toString(), type);

0

结合Gson和JSON(一种不同的方法),适合新手理解。如果您的Gson包含JSON数组。

       ArrayList<Sukh>sukhs new ArrayList<>();
       Gson gson = new Gson();
       try {
           JSONArray jsonArray = new JSONArray(fullJsonArrayString);
           for (int i = 0; i < jsonArray.length(); i++) {
               JSONObject jsonObject=jsonArray.getJSONObject(i);
               Sukh sukhObject = gson.fromJson(jsonObject.toString(), Sukh.class);
               sukhs.add(sukhObject);
           }
       } catch (JSONException e) {
           e.printStackTrace();
       }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接