Convert JSONArray to Object using GSON fromJson method
Solution 1
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
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.
Alireza
I had worked with different Platforms(Such as iOS, PHP, android, Java, windows OS and love Linux OS); To achieve new experiences. I love new challenges; But newly(one recent year) I have full focused on the J2SE, J2EE, Python and JS as scripting languages and somehow PHP. I Love All about Open-source software and wanna join this communicate more deeply. In one hand,I am working on my Ideas and in another,also interested in team-working and work for companies all over the world; via remote or out-source projects to Earn revenue. As I was interested in different platforms, My current position is all about MS and MS solutions. (Develop CRM and SharePoint) But also have some projects for custom requirements, based on J2ee and JS solutions( like Spring, jQuery, react ) This is all about the company, In my free time, I develop and work for my Ideas. Interested and Ready to accept projects.
Updated on July 10, 2022Comments
-
Alireza almost 2 years
I have a
WCF
Webservice
, in which send a data model and i get this inAndroid
byJSon
(By Entity Framework),any ways, I can successfully get thatJSON
by this code and store allJSON
Objects inJSONArray
in theAsyncTas
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
inandroid
, 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 useGSON
instead,any one can help me with this sample? Here is myJSONArray
andJSON
Object :{ "getContactResult": [ { "id": 2041, "lastName": "xxxx", "latitude": xxx, "longitude": xxx, "name": "xxxx", "phoneNumber": "xxxx" } ] }
Thx
-
Alireza over 7 yearsThx dude, I did it before you said, but again thx, and jsonArray should pass as String in the Gson method, so it should be : String.valueOf(jArray) and i made my Contact fileds SerializedName as I edit. Here you can see in edit.
-
Kyon147 about 6 yearsHaving this issue recently, this was exactly what I needed. Thank you!