Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用GSON-fromJson方法将JSONArray转换为对象_Android_Json_Gson - Fatal编程技术网

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

Android 使用GSON-fromJson方法将JSONArray转换为对象,android,json,gson,Android,Json,Gson,我有一个WCFWebservice,其中发送一个数据模型,我通过JSon(通过实体框架)在Android中获得该模型, 我可以通过此代码成功获取JSON,并将所有JSON对象存储在JSONArray的AsyncTas类中,并存储在: public class Consume extends AsyncTask<Void, Void, Void> { InputStream inputStream = null; String resu

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

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();
                }
            }
我用老方法解析这个
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;
        }
Thx

导入com.google.gson.reflect.TypeToken;
导入java.lang.reflect.Type;
列出联系人名单;
类型listType=新类型令牌(){
}.getType();
contacts=new Gson().fromJson(jsonArray,listType);

这应该行得通。确保模型类的名称与json参数和数据类型的名称相同。它将解析jsonarray以键入java的列表

这已经得到了回答,但我想与您分享一件事。简单且最好的方法

android studio有一个插件Gson。您需要安装。然后转到CTRL+insert。 您可以创建gson文件。 为java文件输入一些名称

单击该文件,然后粘贴json数据。单击“确定”。 您可以看到您创建的json到gson格式

谢谢,希望这能对您有所帮助。

结合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();
       }
ArrayListsukhs new ArrayList();
Gson Gson=新的Gson();
试一试{
JSONArray JSONArray=新JSONArray(完整JSONARRAYSTRING);
for(int i=0;i
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
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);
import com.google.gson.reflect.TypeToken;
导入java.lang.reflect.Type;
val gson=gson()
val type=object:TypeToken(){}.type
val listContact:KycProperties=gson.fromJson(jArray.toString(),type)作为联系人
Java解决方案

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
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);
import com.google.gson.reflect.TypeToken;
导入java.lang.reflect.Type;
列表列表联系人;
Type Type=new-TypeToken(){
}.getType();
listContact=new Gson().fromJson(jsonArray.toString(),type);

Gson文档不清楚的地方是什么?另外,也许你应该研究一下Gson转换器的改型你可以试试Thx dude,我在你说之前就做过,但是同样的,Thx和jsonArray应该在Gson方法中作为字符串传递,所以它应该是:String.valueOf(jArray),我在编辑时将我的联系人文件序列化为Name。在这里你可以看到编辑。最近有这个问题,这正是我需要的。非常感谢。
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);