I have a JSON file like this:
[
{
"id": "1",
"name": "test1",
"childrens": [
{
"id": "14",
"name": "test2",
"childrens": [
]
}
]
}
]
The model class:
public class Model {
private int id;
private String name;
}
And my parse method:
public List< Model > parseJSONService(JSONArray jsonArray) {
Gson gson = new Gson();
Model[] model = gson.fromJson(jsonArray.toString(),
Model[].class);
return Arrays.asList(model);
}
why not parse the json string directly? this is what i did, achieved the same thing you looking for i guess:
public class GsonPlay {
public static void main(String args[]) {
String testString = "[{\"id\": \"1\",\"name\": \"test1\",\"childrens\": [{\"id\": \"14\",\"name\": \"test2\",\"childrens\": []}]}]";
List<Model> modelList = parseJsonService(testString);
System.out.println(modelList);
}
private static List<Model> parseJsonService(String testString) {
Gson gson = new Gson();
Model[] models = gson.fromJson(testString, Model[].class);
return Arrays.asList(models);
}
}
class Model {
private int id;
private String name;
private List<Model> childrens;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Model> getChildrens() {
return childrens;
}
public void setChildrens(List<Model> childrens) {
this.childrens = childrens;
}
}
You can also have a look at this for further ideas:
Related
Below is my JSON data. I want to convert this to POJOs to store the Name,id,profession in a header table and the respective Jsonarray field in a child table.
JSON:
{
"Name": "Bob",
"id": 453345,
"Profession": "Clerk",
"Orders": [
{
"Item": "Milk",
"Qty": 3
},
{
"Item": "Bread",
"Qty": 3
}
]
}
Entity classes:
public class User {
private String name;
private Integer id;
private String Profession;
private JsonArray Orders;
private UserCart userCart;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProfession() {
return Profession;
}
public void setProfession(String profession) {
Profession = profession;
}
public JsonArray getOrders() {
return Orders;
}
public void setOrders(JsonArray orders) {
Orders = orders;
}
public UserCart getUserCart() {
return userCart;
}
public void setUserCart(UserCart userCart) {
this.userCart = userCart;
}
}
public class UserCart {
private String item;
private Integer qty;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
}
But when I do below; I get error
Cannot deserialize instance of org.json.JSONArray out of START_ARRAY
token
User user = new User();
JsonNode data = new ObjectMapper().readTree(jsonString);
user = headerMap.readValue(data.toString(), User.class);
How do I go about assigning the entire JSON to both the Java objects ?
Use List<UserCart> for array data in json and use #JsonProperty for mapping different json node name to java object field. No need to use extra field (JsonArray Orders) anymore.
#JsonProperty("Orders")
private List<UserCart> userCart;
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 a String in my servlet which is of the following format.
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"bookName": [
"The Magic",
"The Power"
]
}
where the bookName is an array. I want to access the values in the array and populate in the bean. But, when I try to convert the string to jsonobject, I am getting the following exception because bookName is an array com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY This is how I am trying to do it
JSONObject js= new JSONObject();
String inputData= request.getParameter("inputData");
HashMap<String, String> hmap= new HashMap<String, String>();
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
hmap = gson.fromJson(inputData, type);
js.putAll(hmap);
What I am doing is, I convert the string to a map and then add it to the JSONObject.
Since there are many json serializers and not sure which is the best. Right now, I have net.sf.json.JSONObject and com.google.gson.JsonObject
Can someone help me to get this solved.
Thanks in advance
You can map your JSON to a POJO.
If the book will have more attributes besides the name, you'll need two POJOs, as you can see below.
A POJO for the book:
class Book {
private String name;
private String author;
public Book() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
And a POJO for the shelf, which have a list of books:
class Shelf {
private String name;
private Integer noOfBooksRequired;
private String type;
private List<Book> books;
public Shelf() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNoOfBooksRequired() {
return noOfBooksRequired;
}
public void setNoOfBooksRequired(Integer noOfBooksRequired) {
this.noOfBooksRequired = noOfBooksRequired;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
Your JSON will look like this:
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"books": [
{"name": "The Magic", "author": "John Doe"},
{"name": "The Power", "author": "Jane Doe"}
]
}
And then you can use Gson to parse your JSON:
Gson gson = new Gson();
Shelf shelf = gson.fromJson(inputData, Shelf.class);
Update
Considering your JSON looks like this (the book can be represented as a String):
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"books": [
"The Magic",
"The Power"
]
}
Only one POJO with a list of String is enough:
class Shelf {
private String name;
private Integer noOfBooksRequired;
private String type;
private List<String> books;
public Shelf() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNoOfBooksRequired() {
return noOfBooksRequired;
}
public void setNoOfBooksRequired(Integer noOfBooksRequired) {
this.noOfBooksRequired = noOfBooksRequired;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getBooks() {
return books;
}
public void setBooks(List<String> books) {
this.books = books;
}
}
Given I have the following json:
{
"Company": {
"name": "cookieltd",
"type": "food",
"franchise_location": [
{
"location_type": "town",
"address_1": "5street"
},
{
"location_type": "village",
"address_1": "2road"
}
]
}
}
How can it be binded to the following object classes using Jackson?:
1) Company class
public class Company
{
String name, type;
List<Location> franchise_location = new ArrayList<Location>();
[getters and setters]
}
2) Location class
public class Location
{
String location_type, address_1;
[getters and setters]
}
I have done:
String content = [json above];
ObjectReader reader = mapper.reader(Company.class).withRootName("Company"); //read after the root name
Company company = reader.readValue(content);
but I am getting:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "franchise_location"
As far as I can tell, you are simply missing an appropriately named getter for the field franchise_location. It should be
public List<Location> getFranchise_location() {
return franchise_location;
}
(and the setter)
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
Alternatively, you can annotate your current getter or field with
#JsonProperty("franchise_location")
private List<Location> franchiseLocation = ...;
which helps to map JSON element names that don't really work with Java field name conventions.
The following works for me
public static void main(String[] args) throws Exception {
String json = "{ \"Company\": { \"name\": \"cookieltd\", \"type\": \"food\", \"franchise_location\": [ { \"location_type\": \"town\", \"address_1\": \"5street\" }, { \"location_type\": \"village\", \"address_1\": \"2road\" } ] } }";
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(Company.class).withRootName(
"Company"); // read after the root name
Company company = reader.readValue(json);
System.out.println(company.getFranchise_location().get(0).getAddress_1());
}
public static class Company {
private String name;
private String type;
private List<Location> franchise_location = new ArrayList<Location>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Location> getFranchise_location() {
return franchise_location;
}
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
}
public static class Location {
private String location_type;
private String address_1;
public String getLocation_type() {
return location_type;
}
public void setLocation_type(String location_type) {
this.location_type = location_type;
}
public String getAddress_1() {
return address_1;
}
public void setAddress_1(String address_1) {
this.address_1 = address_1;
}
}
and prints
5street
my solution for JSON is always GSON, you can do some research on that, as long as you have the correct structure of class according to the JSON, it can automatically transfer from JSON to object:
Company company = gson.fromJson(json, Company.class);
GSON is so smart to do the convertion thing!
enjoy GSON !
I am working on facebook application. When i queried for https://graph.facebook.com/me/video.watches?offset=0&limit=1000 I am getting a List of Watched Movies. For eg. I am pasting only one movie out of that list here.
{
"data": [
{
"id": "664878940211923",
"data": {
"tv_show": {
"id": "108611845829948",
"url": "https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type": "video.tv_show",
"title": "Popeye the Sailor"
}
},
"type": "video.watches",
},
Here is the POJO Class I created to convert this to Java.
import java.util.List;
public class FBUserVideoWatches {
private List<Data> data;
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public class Data{
private long id;
private TVData data;
private String type;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public TVData getData() {
return data;
}
public void setData(TVData data) {
this.data = data;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class TVData{
private TV_Shows tv_shows;
public TV_Shows getTv_shows() {
return tv_shows;
}
public void setTv_shows(TV_Shows tv_shows) {
this.tv_shows = tv_shows;
}
}
public class TV_Shows{
private long id;
private String url;
private String type;
private String title;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
Here is how i convert the json to java.
FBUserVideoWatches fbUserVideoWatches = gson.fromJson(response.getBody(), FBUserVideoWatches.class);
for (Data data : fbUserVideoWatches.getData()) {
System.out.println(data.getId());//This only works and I am getting values.
if(null != data.getData()){
if(null!=data.getData().getTv_shows()){
System.out.print(data.getData().getTv_shows().getTitle());
}
if(null!=data.getData().getTv_shows()){
System.out.print(data.getData().getTv_shows().getType());
}
}
}
When I use getter methods to get data from java class I am getting ID 664878940211923 & "type": "video.watches" as shown above. The members inside "tv_show" I am unable to access. I think some where I went wrong in creating POJO. I am unable to find that mistake. Please help me what corrections is necessary to make that work. Hope my question is clear. Thanks in Advance.
You were doing mistake in TVData Class your forgot serialized name on instance property coz its in diffferent in json and TV data class
#SerializedName(value="tv_show")
private TV_Shows tv_shows;
Assuming your json is like this
{
"data":[
{
"id":"664878940211923",
"data":{
"tv_show":{
"id":"108611845829948",
"url":"https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type":"video.tv_show",
"title":"Popeye the Sailor"
}
},
"type":"video.watches"
},
{
"id":"664878940211923",
"data":{
"tv_show":{
"id":"108611845829948",
"url":"https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type":"video.tv_show",
"title":"Popeye the Sailor"
}
},
"type":"video.watches"
}
]
}
Parsing model will like below according you to your json format
public class FBUserVideoWatches {
private List<Data> data;
public List<Data> getData() { return data; }
public void setData(List<Data> data) { this.data = data;}
}
public class Data {
private TVData data;
private String id;
private String type;
// setter/getter here
}
public class TVData {
#SerializedName(value="tv_show")
private Show show;
// setter/getter here
}
public class Show {
private String id;
private String url;
private String type;
private String title;
// setter/getter here
}
finally with Google Gson parse your object as like below
Gson gson = new Gson();
FBUserVideoWatches fbUserVideoWatches =gson.fromJson(json_string, FBUserVideoWatches.class);