使用GSON fromJson方法将JSONArray转换为Object [英] Convert JSONArray to Object using GSON fromJson method

查看:108
本文介绍了使用GSON fromJson方法将JSONArray转换为Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WCF Webservice ,其中发送了一个数据模型,我在 Android by JSon (通过实体框架),任何方式,
我可以成功获取 JSON 中存储 JSONArray 中的所有 JSON 对象。 > AsyncTas 类,并在:

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

InputStream inputStream = null;
String result =;
private ArrayList<联系人> 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>();
尝试{
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();
$ b $ catch(UnsupportedEncoding 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; ((line = bReader.readLine())!= null){
sBuilder.append(line +\\\
);
}
inputStream.close();
result = sBuilder.toString();
} catch(Exception e){
Log.e(StringBuilding,Error conversion result+ e.toString());
}
返回null;
}

@Override
protected void onPostExecute(void aVoid){
super.onPostExecute(aVoid);
try {
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray(getContactResult); //这里我创建了所有JsonObjects的JsonArray

//下面是解决方案,我们列出out联系人并将其设置为down

List< Contact>联系人;
type listType = new TypeToken< List< Contact>>(){
} .getType();
contacts = new Gson()。fromJson(String.valueOf(jArray),listType);

//这里解决方案结束了!

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


我创建了一个Contact
$ b $ android 通过以下代码: c> public class Contact {


@SerializedName(name)
private String name;

@SerializedName(lastName)
private String lastName;

@SerializedName(phoneNumber)
private String phoneNumber;

@SerializedName(纬度)
私人字符串纬度;

@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对象=(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();
}
}
返回联系人;
}

它可以工作,但我不想处理和解析 JSONArray 按照这种方式,并且想要使用 GSON ,任何人都可以帮我解决这个问题。
这是我的 JSONArray JSON 对象:

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

Thx

解决方案

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

列表<联系人>联系人;
type listType = new TypeToken< List< Contact>>(){
} .getType();
contacts = new Gson()。fromJson(jsonArray,listType);

这应该有效。确保你的模型类具有与json参数和数据类型相同的名称。它将解析 jsonarray 以键入 List 的java


I have a WCF Webservice, in which send a data model and i get this in Android by JSon(By Entity Framework),any ways, I can successfully get that JSON by this code and store all JSON Objects in JSONArray in the AsyncTas class, and in :

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

And i created a Contact class in android, by this code :

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

And i parse this JSONArray by Old ways ! By this method :

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

It works, but I do not want to handle and parse JSONArray by this old way and wanna use GSON instead,any one can help me with this sample? Here is my JSONArray and JSON Object :

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

Thx

解决方案

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

This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java

这篇关于使用GSON fromJson方法将JSONArray转换为Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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