I am using Retrofit android library and Gson converter to get JSON response from my server,
this is the response. After receiving the response my app is crashing in onCreate()API. Could anyone suggest me what is wrong with below code?
{
"content": [
{
"id": 1,
"title": "Xrp the standard",
"desc": "Hodl till you die",
"createdBy": {
"id": 1,
"username": "1",
"name": "Radovan"
},
"creationDateTime": {
"epochSecond": 1533679200,
"nano": 0
},
"photo": "to_the_moon.jpg",
"tags": "tagovi",
"likes": 12,
"dislikes": 2,
"comments": [
{
"id": 1,
"title": "Bravo nasi",
"desc": "Samo sloga Srbina spasava",
"createdBy": {
"id": 2,
"username": "",
"name": ""
},
"creationDateTime": {
"epochSecond": 1533679200,
"nano": 0
},
"likes": 3,
"dislikes": 4
}
]
}
],
"page": 0,
"size": 30,
"totalElements": 1,
"totalPages": 1,
"last": true
}
This is my Retro client,
public class RetroClient {
private static final String BASE_URL = "http://192.189.0.27:8080/";
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static RestAPI getRestAPI() {
return getRetrofitInstance().create(RestAPI.class);
}
}
This is my rest api call
#GET("api/posts")
Call<Example> getPosts();
My Example class
public class Example {
#SerializedName("content")
#Expose
private List<Content> content;
#SerializedName("page")
#Expose
private Integer page;
#SerializedName("size")
#Expose
private Integer size;
#SerializedName("totalElements")
#Expose
private Integer totalElements;
#SerializedName("totalPages")
#Expose
private Integer totalPages;
#SerializedName("last")
#Expose
private Boolean last;
public Example() {
}
public Example(List<Content> content, Integer page, Integer size, Integer totalElements, Integer totalPages, Boolean last) {
super();
this.content = content;
this.page = page;
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
this.last = last;
}
//Getters and setters
My Content class (nested array of objects which I need access to, "content" in response)
public class Content {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("desc")
#Expose
private String desc;
#SerializedName("createdBy")
#Expose
private CreatedBy createdBy;
#SerializedName("creationDateTime")
#Expose
private CreationDateTime creationDateTime;
#SerializedName("photo")
#Expose
private String photo;
#SerializedName("tags")
#Expose
private String tags;
#SerializedName("likes")
#Expose
private Integer likes;
#SerializedName("dislikes")
#Expose
private Integer dislikes;
#SerializedName("comments")
#Expose
private List<CommentResponse> comments;
public Content() {
}
public Content(Integer id, String title, String desc, CreatedBy createdBy, CreationDateTime creationDateTime, String photo, String tags, Integer likes, Integer dislikes, List<CommentResponse> comments) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.createdBy = createdBy;
this.creationDateTime = creationDateTime;
this.photo = photo;
this.tags = tags;
this.likes = likes;
this.dislikes = dislikes;
this.comments = comments;
}
//Getters and setters
and finally, my callback method in onCreate
RestAPI rest_api = RetroClient.getRestAPI();
Call<Example> call = rest_api.getPosts();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if( response.isSuccessful()) {
//here, I need to get "content" so I could fill up list in code below,
//tried almost everything, but activity crashes when created
postsList = response.body().getContent();
for(int i = 0; i < postsList.size(); i++) {
Content content = postsList.get(i);
pAdapter.addPost(content);
}
}
else {
int sc = response.code();
switch (sc) {
}
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Add getters and setters for list "content" in Example class and do this "response.body().getContent()" to get the list.
postsList = response.body().getContent();
Your Pojos should implements Parcelable interface
public class Example implements Parcelable {
//your members
}
Related
De-Serializing Objects within a List
I currently have an 'Admin' Entity in which upon a GET Request of AllAdmin() will return me the following response. This was used in Postman.
GET Response for AllAdmin() [POSTMAN]
[
{
"adminId": 1,
"fullName": "Patrick ",
"email": "patrick#gmail.com",
"dob": "1669-12-12",
"mobileNumber": "96369636",
"password": "password123!",
"usages": [
{
"id": 3,
"datetimeUnlocked": "2021-06-07 10:12:23"
},
{
"id": 4,
"datetimeUnlocked": "2021-06-07 10:12:27"
}
],
"authorization": [
{
"id": 2,
"datetimeAccepted": "2021-06-07 10:12:14"
}
],
"adminAllow": []
},
{
"adminId": 2,
"fullName": "Worker ",
"email": "worker#gmail.com",
"dob": "2000-12-12",
"mobileNumber": "96399639",
"password": "password123!",
"usages": [],
"authorization": [],
"adminAllow": []
} ]
The current code is my Admin Model in my Android Application.
Admin.java Model Class
public class Admin {
#SerializedName("adminId")
private long adminID;
#SerializedName("fullName")
private String adminFullName;
#SerializedName("email")
private String adminEmail;
#SerializedName("dob")
private String adminDOB;
#SerializedName("mobileNumber")
private String adminMobileNumber;
// Constructor
public Admin(long adminID, String adminFullName, String adminEmail, String adminDOB, String adminMobileNumber) {
this.adminID = adminID;
this.adminFullName = adminFullName;
this.adminEmail = adminEmail;
this.adminDOB = adminDOB;
this.adminMobileNumber = adminMobileNumber;
}
// Getter
public long getAdminID() {
return adminID;
}
public String getAdminFullName() {
return adminFullName;
}
public String getAdminEmail() {
return adminEmail;
}
public String getAdminDOB() {
return adminDOB;
}
public String getAdminMobileNumber() {
return adminMobileNumber;
}
}
I would like to clarify on how I would de-serialize the usages and authorization properties so that I am able to access and manipulate the data entries for these?
I thank you in advance for your clarifications!
For usages, you should use a List<Usage> as the serializable. My assumption is you are using Retrofit. So the Retrofit Gson converter will take care of parsing the array of Usage. The same logic would apply for authorization. You can use the different key there for the datetimeAccepted case.
Check this sample for Usage
public class Usage {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("datetimeUnlocked")
#Expose
private String datetimeUnlocked;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDatetimeUnlocked() {
return datetimeUnlocked;
}
public void setDatetimeUnlocked(String datetimeUnlocked) {
this.datetimeUnlocked = datetimeUnlocked;
}
}
Your updated Admin class must look like this
public class Admin {
#SerializedName("adminId")
private long adminID;
#SerializedName("fullName")
private String adminFullName;
#SerializedName("email")
private String adminEmail;
#SerializedName("dob")
private String adminDOB;
#SerializedName("mobileNumber")
private String adminMobileNumber;
#SerializedName("usages")
private List<Usage> usages;
// Constructor
public Admin(long adminID, String adminFullName, String adminEmail, String adminDOB, String adminMobileNumber, List<Usage> usages) {
this.adminID = adminID;
this.adminFullName = adminFullName;
this.adminEmail = adminEmail;
this.adminDOB = adminDOB;
this.adminMobileNumber = adminMobileNumber;
this.usages = usages;
}
// Getter
public long getAdminID() {
return adminID;
}
public String getAdminFullName() {
return adminFullName;
}
public String getAdminEmail() {
return adminEmail;
}
public String getAdminDOB() {
return adminDOB;
}
public String getAdminMobileNumber() {
return adminMobileNumber;
}
public List<Usage> getUsages() {
return usages;
}
}
I am creating an app using RetroFit. I am getting the Data from JSON string from URL and populate it in Recycle view using RetroFit.
My Problem
My problem is , when the app executed, it shows the following errors::
E/RecyclerView: No adapter attached; skipping layout E/RecyclerView:
No adapter attached; skipping layout D/Error:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 1 column 2 path $
My Checkings
Checked the URL
Checked URL using Browser.. It returns json successfully
I tried hard to resove this problem , But no solution.
I manually ran the json url and JSON data returned successfully. But on program , it is returning errors.
JSON DATA SAMPLE
[
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59eeb10d40d16686168b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
"post_type": "image",
"caption": "vvnnk",
"created": 1508815117,
"time_diff": "1 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "New release"
},
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59ee306940d166697f8b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
"post_type": "image",
"caption": "cutyy",
"created": 1508782185,
"time_diff": "10 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "Super Star"
}
]
Post.java (POJO for JSON)
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Post {
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("post_id")
#Expose
private String postId;
#SerializedName("post_url")
#Expose
private String postUrl;
#SerializedName("post_type")
#Expose
private String postType;
#SerializedName("caption")
#Expose
private String caption;
#SerializedName("created")
#Expose
private Integer created;
#SerializedName("time_diff")
#Expose
private String timeDiff;
#SerializedName("first_name")
#Expose
private Object firstName;
#SerializedName("last_name")
#Expose
private Object lastName;
#SerializedName("user_name")
#Expose
private Object userName;
#SerializedName("email")
#Expose
private Object email;
#SerializedName("profile_pic")
#Expose
private String profilePic;
#SerializedName("category")
#Expose
private String category;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getPostUrl() {
return postUrl;
}
public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public Integer getCreated() {
return created;
}
public void setCreated(Integer created) {
this.created = created;
}
public String getTimeDiff() {
return timeDiff;
}
public void setTimeDiff(String timeDiff) {
this.timeDiff = timeDiff;
}
public Object getFirstName() {
return firstName;
}
public void setFirstName(Object firstName) {
this.firstName = firstName;
}
public Object getLastName() {
return lastName;
}
public void setLastName(Object lastName) {
this.lastName = lastName;
}
public Object getUserName() {
return userName;
}
public void setUserName(Object userName) {
this.userName = userName;
}
public Object getEmail() {
return email;
}
public void setEmail(Object email) {
this.email = email;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Post> post;
public DataAdapter(ArrayList<Post> post) {
this.post = post;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_userId.setText(post.get(i).getUserId());
viewHolder.tv_postId.setText(post.get(i).getPostId());
viewHolder.tv_postType.setText(post.get(i).getPostType());
viewHolder.tv_caption.setText(post.get(i).getCaption());
Picasso.with(viewHolder.tv_postUrl.getContext()).load(post.get(i).getPostUrl()).into(viewHolder.tv_postUrl);
Picasso.with(viewHolder.tv_profilePic.getContext()).load(post.get(i).getProfilePic()).into(viewHolder.tv_profilePic);
viewHolder.tv_timeDiff.setText(post.get(i).getTimeDiff());
viewHolder.tv_category.setText(post.get(i).getCategory());
viewHolder.tv_created.setText(post.get(i).getCreated());
}
#Override
public int getItemCount() {
return post.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_userId,tv_postId,tv_postType,tv_caption,tv_timeDiff,tv_category,tv_created;
ImageView tv_profilePic,tv_postUrl;
public ViewHolder(View view) {
super(view);
tv_userId = (TextView)view.findViewById(R.id.tv_userId);
tv_postUrl = (ImageView) view.findViewById(R.id.tv_postUrl);
tv_postType = (TextView)view.findViewById(R.id.tv_postType);
tv_caption = (TextView)view.findViewById(R.id.tv_caption);
tv_postId = (TextView)view.findViewById(R.id.tv_postId);
tv_timeDiff = (TextView)view.findViewById(R.id.tv_timeDiff);
tv_profilePic = (ImageView)view.findViewById(R.id.tv_profilePic);
tv_category = (TextView)view.findViewById(R.id.tv_category);
tv_created = (TextView)view.findViewById(R.id.tv_created);
}
}
}
JSONResponse.java
public class JSONResponse {
private Post[] post;
public Post[] getPost() {
return post;
}
}
RequestInterface.java
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
#GET("anan/mobile/posts/viewall_Posts")
Call<JSONResponse> getJSON();
}
MainActitvity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<Post> data;
private DataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://demo.cogzideltemplates.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
System.out.println("enter the url: "+call.request().url());
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getPost()));
adapter = new DataAdapter(data);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
These are my classes. Please hekp me to resolve this problem.
change your JSON data sample to JSON object
Like this
{
[
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59eeb10d40d16686168b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
"post_type": "image",
"caption": "vvnnk",
"created": 1508815117,
"time_diff": "1 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "New release"
},
{
"user_id": "59e4897140d1666c6e8b4567",
"post_id": "59ee306940d166697f8b4567",
"post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
"post_type": "image",
"caption": "cutyy",
"created": 1508782185,
"time_diff": "10 hours ago",
"first_name": null,
"last_name": null,
"user_name": null,
"email": null,
"profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
"category": "Super Star"
}
]}
And Change your JSONResponse.java
Like this
public class JSONResponse {
private List<Post> post;
public List<Post> getPost() {
return post;
}
}
Here is the tutorial for parsing JSON Array and JSON Object
I have following JSON structure:
{
"result": {
"category": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}]
}]
},
{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}
]
}
}
I need to create class with the above JSON.
I have created two classes as HomeCategoryModel and HomeSubCategoryModel.
There may be multiple sub-categories in each level.
How to map this type of json into classes.
HomeCategoryModel class:
public class HomeCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//...
//getter, setter
}
HomeSubCategory class:
public class HomeSubCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//getter setter
}
I have tried to parse using recursive function like this but doesn't seem to work:
JSONObject allLists = jsonObject.getJSONObject("result");
JSONArray catArray = allLists.getJSONArray("category");
ArrayList<HomeCategoryModel> categoryList = new ArrayList<HomeCategoryModel>();
for (int i = 0; i < catArray.length(); i++) {
JSONObject jObj = catArray.getJSONObject(i);
HomeCategoryModel categoryModel = new HomeCategoryModel();
categoryModel.setId(Integer.parseInt(jObj.getString("id")));
categoryModel.setName(jObj.getString("name"));
categoryModel.setSlug(jObj.getString("slug"));
categoryModel.setImageUrl(jObj.getString("image"));
JSONArray productsArray = jObj.getJSONArray("sub-categories");
if (productsArray.length() > 0) {
parseSubCategories(productsArray);
}
categoryList.add(categoryModel);
}
And:
public static ArrayList<HomeSubCategoryModel> parseSubCategories(JSONArray arr) {
ArrayList<HomeSubCategoryModel> subLists = new ArrayList<HomeSubCategoryModel>();
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject childObj = arr.getJSONObject(i);
HomeSubCategoryModel categoryModel = new HomeSubCategoryModel();
categoryModel.setId(Integer.parseInt(childObj.getString("id")));
categoryModel.setName(childObj.getString("name"));
categoryModel.setSlug(childObj.getString("slug"));
categoryModel.setImageUrl(childObj.getString("image"));
JSONArray subArray = childObj.getJSONArray("sub-categories");
if (subArray.length() > 0) {
parseSubCategories(subArray);
}
subLists.add(categoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
return subLists;
}
Please suggest me. Thank you.
if you would like to use Gson then i can suggest something like below.
Generate your POJO like this
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public class Result {
#SerializedName("category")
#Expose
private List < Category > category = null;
public List < Category > getCategory() {
return category;
}
public void setCategory(List < Category > category) {
this.category = category;
}
}
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < SubCategory > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < SubCategory > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < SubCategory > subCategories) {
this.subCategories = subCategories;
}
}
public class SubCategory_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < Object > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < Object > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < Object > subCategories) {
this.subCategories = subCategories;
}
}
}
and then
Gson gson = new Gson();
Example exp = gson.fromJson("your json string",Example.class);
And you are done.
I have an Array of Json elements as a String, my problem is how to convert them into and Object Array using Gson.
I found some methods on this site but non of them seem to work for my String.
["2": {"id": 2, "name": "Cannonball", "sp": 5, "overall_average": 194, "buy_average": 193, "members": true, "sell_average": 193},
"6": {"id": 6, "name": "Cannon base", "sp": 187500, "overall_average": 188110, "buy_average": 184547, "members": true, "sell_average": 185735},
"12289": {"id": 12289, "name": "Mithril platelegs (t)", "sp": 2600, "overall_average": 0, "buy_average": 3000, "members": false, "sell_average": 3000},
"8": {"id": 8, "name": "Cannon stand", "sp": 187500, "overall_average": 198445, "buy_average": 189001, "members": true, "sell_average": 190889},
"10": {"id": 10, "name": "Cannon barrels", "sp": 187500, "overall_average": 194418, "buy_average": 185164, "members": true, "sell_average": 185935},
"12": {"id": 12, "name": "Cannon furnace", "sp": 187500, "overall_average": 188000, "buy_average": 186524, "members": true, "sell_average": 186637},
"4099": {"id": 4099, "name": "Mystic hat (dark)", "sp": 15000, "overall_average": 9758, "buy_average": 9229, "members": true, "sell_average": 9528}]
I need to convert the data to this java object.
public class OSBuddyItem {
private final int id;
private final String name;
private final int sellPrice;
private final int buyPrice;
private final int averagePrice;
private final int storePrice;
private final boolean members;
public OSBuddyItem(int id, String name, int sellPrice, int buyPrice, int averagePrice, int storePrice, boolean members){
this.id = id;
this.name = name;
this.sellPrice = sellPrice;
this.buyPrice = buyPrice;
this.averagePrice = averagePrice;
this.storePrice = storePrice;
this.members = members;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getSellPrice() {
return sellPrice;
}
public int getBuyPrice() {
return buyPrice;
}
public int getAveragePrice() {
return averagePrice;
}
public int getStorePrice() {
return storePrice;
}
public boolean isMembers() {
return members;
}
}
This is what I tried:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(data);
JsonArray itemElements = tradeElement.getAsJsonArray();
OSBuddyItem[] items = gson.fromJson(itemElements,OSBuddyItem[].class);
for(OSBuddyItem item : items){
System.out.println(item.getName());
}
Can someone please tell me how to convert the String using Gson?
Your JSON String is not valid.You can validate your JSON String from [http://jsoneditoronline.org/][1]
Suppose if JSON String is in form :-
[{"1": {"id": 2, "name": "Cannonball", "sp": 5, "overall_average": 194, "buy_average": 193, "members": true, "sell_average": 193}}]
Suppose Model Name is Example.Then Model of Json will be :-
package com.example;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("id")
private Integer id;
#SerializedName("name")
private String name;
#SerializedName("sp")
private Integer sp;
#SerializedName("overall_average")
private Integer overallAverage;
#SerializedName("buy_average")
private Integer buyAverage;
#SerializedName("members")
private Boolean members;
#SerializedName("sell_average")
private Integer sellAverage;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSp() {
return sp;
}
public void setSp(Integer sp) {
this.sp = sp;
}
public Integer getOverallAverage() {
return overallAverage;
}
public void setOverallAverage(Integer overallAverage) {
this.overallAverage = overallAverage;
}
public Integer getBuyAverage() {
return buyAverage;
}
public void setBuyAverage(Integer buyAverage) {
this.buyAverage = buyAverage;
}
public Boolean getMembers() {
return members;
}
public void setMembers(Boolean members) {
this.members = members;
}
public Integer getSellAverage() {
return sellAverage;
}
public void setSellAverage(Integer sellAverage) {
this.sellAverage = sellAverage;
}
}
And using GSON ,you can convert like below.
[Note :TypeToken class is used to load JSON String into a custom Object]
List<Example> myList = new Gson().fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
As you can see the objects matchField and actions are arrays holding objects having different members. Please say what should be my class structure to get this JSON data parsed so that I can get all the data (Please note that the objects in n matchField and actions can have other members- not only the ones in this response). Also is there any other way with GSON(other than using gson.fromJson) to get this done?
{
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"flowStatistic": [
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"mask": "255.255.255.255",
"type": "NW_DST",
"value": "10.0.0.1"
}
]
},
"actions": [
{
"type": "SET_DL_DST",
"address": "7a11761ae595"
},
{
"type": "OUTPUT",
"port": {
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"id": "1",
"type": "OF"
}
}
],
"priority": 1,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62500,
"durationNanoseconds": 513000000,
"packetCount": 0,
"byteCount": 0
},
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"mask": "255.255.255.255",
"type": "NW_DST",
"value": "10.0.0.2"
}
]
},
"actions": [
{
"type": "OUTPUT",
"port": {
"node": {
"id": "00:00:00:00:00:00:00:01",
"type": "OF"
},
"id": "2",
"type": "OF"
}
}
],
"priority": 1,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62500,
"durationNanoseconds": 508000000,
"packetCount": 0,
"byteCount": 0
},
{
"flow": {
"match": {
"matchField": [
{
"type": "DL_TYPE",
"value": "2048"
},
{
"type": "IN_PORT",
"value": "OF|2#OF|00:00:00:00:00:00:00:01"
}
]
},
"actions": [
{
"type": "SET_NW_TOS",
"tos": 30
}
],
"priority": 500,
"idleTimeout": 0,
"hardTimeout": 0,
"id": 0
},
"tableId": 0,
"durationSeconds": 62252,
"durationNanoseconds": 633000000,
"packetCount": 0,
"byteCount": 0
}
]
}
Following are the POJOs created
public class FlowStatisticsList {
#Expose
#SerializedName("node")
private Node node;
#Expose
#SerializedName("flowStatistic")
private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public List<FlowStatistic> getFlowStatistic() {
return flowStatistic;
}
public void setFlowStatistic(List<FlowStatistic> flowStatistic) {
this.flowStatistic = flowStatistic;
}
}
public class FlowStatistic {
#Expose
#SerializedName("flow")
private Flow flow;
#Expose
#SerializedName("tableId")
private long tableId;
#Expose
#SerializedName("durationSeconds")
private long durationSeconds;
#Expose
#SerializedName("durationNanoseconds")
private long durationNanoseconds;
#Expose
#SerializedName("packetCount")
private long packetCount;
#Expose
#SerializedName("byteCount")
private long byteCount;
public Flow getFlow() {
return flow;
}
public void setFlow(Flow flow) {
this.flow = flow;
}
public long getTableId() {
return tableId;
}
public void setTableId(long tableId) {
this.tableId = tableId;
}
public long getDurationSeconds() {
return durationSeconds;
}
public void setDurationSeconds(long durationSeconds) {
this.durationSeconds = durationSeconds;
}
public long getDurationNanoseconds() {
return durationNanoseconds;
}
public void setDurationNanoseconds(long durationNanoseconds) {
this.durationNanoseconds = durationNanoseconds;
}
public long getPacketCount() {
return packetCount;
}
public void setPacketCount(long packetCount) {
this.packetCount = packetCount;
}
public long getByteCount() {
return byteCount;
}
public void setByteCount(long byteCount) {
this.byteCount = byteCount;
}
}
public class Flow {
#Expose
#SerializedName("match")
private Match match;
#Expose
#SerializedName("actions")
private List<Action> actions = new ArrayList<Action>();
#Expose
#SerializedName("priority")
private long priority;
#Expose
#SerializedName("idleTimeout")
private long idleTimeout;
#Expose
#SerializedName("hardTimeout")
private long hardTimeout;
#Expose
#SerializedName("id")
private long id;
public Match getMatch() {
return match;
}
public void setMatch(Match match) {
this.match = match;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
public long getPriority() {
return priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public long getIdleTimeout() {
return idleTimeout;
}
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
}
public long getHardTimeout() {
return hardTimeout;
}
public void setHardTimeout(long hardTimeout) {
this.hardTimeout = hardTimeout;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
public class Match {
#Expose
#SerializedName("matchField")
private List<MatchField> matchField = new ArrayList<MatchField>();
public List<MatchField> getMatchField() {
return matchField;
}
public void setMatchField(List<MatchField> matchField) {
this.matchField = matchField;
}
}
I'm stuck at creating POJOs for Action and MatchField.
The following snippet is used to deserialize the response
gson.fromJson(jsonString, FlowStatisticsList.class)
The following are the POJO classes that you need to create to parse the JSON data into corresponding java object
FlowStatisticsList:
public class FlowStatisticsList {
private Node node;
private List<FlowStatistic> flowStatistic = new ArrayList<FlowStatistic>();
// getters, setters & toString methods
}
Node:
public class Node {
private String id;
private String type;
// getters, setters & toString methods
}
FlowStatistic:
public class FlowStatistic {
private Flow flow;
private long tableId;
private long durationSeconds;
private long durationNanoseconds;
private long packetCount;
private long byteCount;
// getters, setters & toString methods
}
Flow:
public class Flow {
private Match match;
private List<Action> actions = new ArrayList<Action>();
private long priority;
private long idleTimeout;
private long hardTimeout;
private long id;
// getters, setters & toString methods
}
Match:
public class Match {
private List<MatchField> matchField = new ArrayList<MatchField>();
// getters, setters & toString methods
}
MatchField:
public class MatchField {
private String mask;
private String type;
private String value;
// getters, setters & toString methods
}
Action:
public class Action {
private String type;
private String address;
private int tos;
private Port port;
// getters, setters & toString methods
}
Port:
public class Port {
private Node node;
private String type;
private String id;
// getters, setters & toString methods
}
and finally the parsing is as follows:
Gson gson = new GsonBuilder().create();
FlowStatisticsList object = gson.fromJson(jsonData, FlowStatisticsList.class);
System.out.println(object);