Skip to content Skip to sidebar Skip to footer

Convert Jsonarray To Object Using Gson Fromjson Method

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 JSO

Solution 1:

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

List<Contact> contacts;    
TypelistType=newTypeToken<List<Contact>>() {
                    }.getType();
 contacts= newGson().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

Solution 2:

This already answered but i want to share one thing for you.Easy and best way

There is one plugin Gson for android studio.You need to install.Then go to CTRL + insert. You can create gson file. Enter some name for java file.

Click that file then Paste you json data. Click ok. You can see your created json to gson format.

thanks hope this will help you.

Solution 3:

Combining Gson and JSON (a different approach), Simple for newbies to understand. If your gson containing json array.

ArrayList<Sukh>sukhs newArrayList<>();
       Gson gson = newGson();
       try {
           JSONArray jsonArray = newJSONArray(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();
       }

Solution 4:

Kotlin Solution

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 Solution

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

List<Contact> listContact;    
Typetype=newTypeToken<List<Contact>>() {
                }.getType();
listContact= newGson().fromJson(jsonArray.toString(), type);

Post a Comment for "Convert Jsonarray To Object Using Gson Fromjson Method"