I'm trying to read a JSON file that contains an array of different bikes. When trying to print out the bikes to the java console, i keep getting a null point exception. I'm going to make it so that all the bikes are made into object, but for now just looking on how to print them out.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/bikes.json"));
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject);
JSONArray bikeList = (JSONArray) jsonObject.get("BikeList");
Iterator<String> iterator = bikeList.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
JSON File:
{
"Search": {
"BikeList": [
{
"weight": "14.8",
"colour": "Blue",
"price": 149.99,
"name": "Hybrid Pro"
},
{
"weight": "15.8",
"colour": "Red",
"price": 249.99,
"name": "Slant comp"
},
{
"weight": "17.9",
"colour": "Pink",
"price": 500.00,
"name": "Charm"
}
]
}
}
First you have to get the "Search" object. And also you can't just print the object. You need to fetch all the attributes:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/bikes.json"));
JSONObject jsonObject = (JSONObject) obj;
// System.out.println(jsonObject);
JSONObject search = (JSONObject) jsonObject.get("Search");
JSONArray bikeList = (JSONArray) search.get("BikeList");
for (int i = 0; i < bikeList.size(); i++) {
JSONObject bike = (JSONObject) bikeList.get(i);
System.out.println("********************");
System.out.println("Weight: " + bike.get("weight"));
System.out.println("Colour: " + bike.get("colour"));
System.out.println("Price: " + bike.get("price"));
System.out.println("Name: " + bike.get("name"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Why Don't you try this.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/bikes.json"));
JSONObject jsonObject = (JSONObject) obj;
//System.out.println(jsonObject);
*JSONArray Search= (JSONArray) jsonObject.get("Search");
JSONArray bikeList = (JSONArray) Search.get("BikeList");*
Iterator<String> iterator = bikeList.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
instead of
JSONArray bikeList = (JSONArray) jsonObject.get("BikeList");
you have to use the arrayBuilder like this
JsonArray array = Json.createArrayBuilder().build();
in an example:
[
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
JsonArray value = Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567"))
.build();
quick info here
JsonArray
or here
How to create correct JsonArray in Java using JSONObject
Your object is null because, it does not exist. For that you need to have a schema for JSON document like this,
{
"BikeList": [
The above code contains, a first-level BikeList. Which you would then capture from the code. This is the mistake in your code. I believe, you need to read the Search node first, and then move down to the next one to capture the list,
{
"Search": { // This one first.
"BikeList": [
That way, you would first require to get the Search object, then get the BikeList, otherwise it will always be null.
// Search is an object, not an array.
JSONObject search = (JSONObject) jsonObject.get("Search");
// Find the list in the search object.
Rest of code is the one you already have. This would get the list for you.
Create java Pojos and annotate with Jackson 2
package com.example;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "Search" })
public class Bike {
#JsonProperty("Search")
private Search search;
/**
* No args constructor for use in serialization
*
*/
public Bike() {
}
/**
*
* #param search
*/
public Bike(final Search search) {
super();
this.search = search;
}
#JsonProperty("Search")
public Search getSearch() {
return search;
}
#JsonProperty("Search")
public void setSearch(final Search search) {
this.search = search;
}
#Override
public String toString() {
return "Bike [search=" + search + "]";
}
}
package com.example;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "BikeList" })
public class Search {
#JsonProperty("BikeList")
private List<BikeList> bikeList = null;
/**
* No args constructor for use in serialization
*
*/
public Search() {
}
/**
*
* #param bikeList
*/
public Search(final List<BikeList> bikeList) {
super();
this.bikeList = bikeList;
}
#JsonProperty("BikeList")
public List<BikeList> getBikeList() {
return bikeList;
}
#JsonProperty("BikeList")
public void setBikeList(final List<BikeList> bikeList) {
this.bikeList = bikeList;
}
#Override
public String toString() {
return "Search [bikeList=" + bikeList + "]";
}
}
package com.example;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "weight", "colour", "price", "name" })
public class BikeList {
#JsonProperty("weight")
private String weight;
#JsonProperty("colour")
private String colour;
#JsonProperty("price")
private Double price;
#JsonProperty("name")
private String name;
/**
* No args constructor for use in serialization
*
*/
public BikeList() {
}
/**
*
* #param colour
* #param price
* #param weight
* #param name
*/
public BikeList(final String weight, final String colour, final Double price, final String name) {
super();
this.weight = weight;
this.colour = colour;
this.price = price;
this.name = name;
}
#JsonProperty("weight")
public String getWeight() {
return weight;
}
#JsonProperty("weight")
public void setWeight(final String weight) {
this.weight = weight;
}
#JsonProperty("colour")
public String getColour() {
return colour;
}
#JsonProperty("colour")
public void setColour(final String colour) {
this.colour = colour;
}
#JsonProperty("price")
public Double getPrice() {
return price;
}
#JsonProperty("price")
public void setPrice(final Double price) {
this.price = price;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(final String name) {
this.name = name;
}
#Override
public String toString() {
return "BikeList [weight=" + weight + ", colour=" + colour + ", price=" + price + ", name=" + name + "]";
}
}
Then employ Jackson to read input json and convert to Java Objects
package com.example;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class Stackoverflow {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final ObjectReader OBJECT_READER_BIKE = OBJECT_MAPPER.readerFor(Bike.class);
public static void main(final String[] args) throws IOException {
final Bike bike = OBJECT_READER_BIKE.readValue(new File("input/bike.json"));
System.out.println(bike);
}
}
output obtained:-
Bike [search=Search [bikeList=[BikeList [weight=14.8, colour=Blue, price=149.99, name=Hybrid Pro], BikeList [weight=15.8, colour=Red, price=249.99, name=Slant comp], BikeList [weight=17.9, colour=Pink, price=500.0, name=Charm]]]]
Related
I want to read a json file and store it into objects so that I can use it in my logic. After multiple attempts I was able to fetch the json into a Map. But I want the values to be stored in object and not a map.
Below is my code where I tried to fetch it and store in Currency object.
package com.springboot.currencyExchange;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import com.springboot.currencyExchange.model.*;
import com.springboot.currencyExchange.model.Currency;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.springboot.currencyExchange.service.MarketStrategyImpl;
#SpringBootApplication
public class CurrencyExchangeApplication {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
// SpringApplication.run(CurrencyExchangeApplication.class, args);
Object obj = new JSONParser().parse(new FileReader(
"*absolute path*\AvailableMarket.json"));
JSONObject jobj = (JSONObject) obj;
JSONArray ja = (JSONArray) jobj.get("currencies");
Iterator<Currency> itr1 = null;
Iterator<CurrentMarket> itr2 = ja.iterator();
while (itr2.hasNext()) {
itr1 = (Iterator<Currency>) (((List) itr2.next()).iterator());
while (itr1.hasNext()) {
Currency pair = itr1.next();
// System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
Below is my JSON file
{
"currencies": [
{
"currencyName": "Euro",
"price": 80
},
{
"currencyName": "Pound",
"price": 90
},
{
"currencyName": "USD",
"price": 75
}
],
"trades": [
{
"take": "Euro",
"give": "USD"
},
{
"take": "USD",
"give": "Pound"
}
]
}
Below are the POJO classes I created to store the JSON values:
package com.springboot.currencyExchange.model;
import java.util.List;
public class CurrentMarket {
public List<Currency> currency;
public List<Trade> trade;
public CurrentMarket() {
super();
}
public List<Currency> getCurrency() {
return currency;
}
public void setCurrency(List<Currency> currency) {
this.currency = currency;
}
public List<Trade> getTrade() {
return trade;
}
public CurrentMarket(List<Currency> currency, List<Trade> trade) {
super();
this.currency = currency;
this.trade = trade;
}
#Override
public String toString() {
return "CurrentMarket [currency=" + currency + ", trade=" + trade + "]";
}
public void setTrade(List<Trade> trade) {
this.trade = trade;
}
}
Currency.java
package com.springboot.currencyExchange.model;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Currency implements Serializable{
String currencyName;
Double price;
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Override
public String toString() {
return "Currency [currencyName=" + currencyName + ", price=" + price + "]";
}
public Currency(String currencyName, Double price) {
super();
this.currencyName = currencyName;
this.price = price;
}
}
Trade.java
package com.springboot.currencyExchange.model;
import java.util.ArrayList;
public class Trade {
ArrayList<String> take;
ArrayList<String> give;
public ArrayList<String> getTake() {
return take;
}
public Trade(ArrayList<String> take, ArrayList<String> give) {
super();
this.take = take;
this.give = give;
}
public void setTake(ArrayList<String> take) {
this.take = take;
}
public ArrayList<String> getGive() {
return give;
}
public void setGive(ArrayList<String> give) {
this.give = give;
}
}
I also tried the GSON approach but couldn't fetch it in desired format.
Below is the error message I get with current setup:
Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List (org.json.simple.JSONObject is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at com.springboot.currencyExchange.CurrencyExchangeApplication.main(CurrencyExchangeApplication.java:32)
I am not sure how else can I proceed. Any help would be appreciated.
You need to make a few changes at first.
As Abrar Ansari said, change the type of the variables from ArrayList to String in the Trade class. Also rename the currency and trade variables from the CurrencyMarket class to currencies and trades. Make all fields private in all model classes and make sure you have default constructors in all model classes. Then use Jackson's ObjectMapper to deserialize the json file into an object of type CurrentMarket:
ObjectMapper objectMapper = new ObjectMapper();
CurrentMarket currentMarket = objectMapper.readValue(new ClassPathResource("AvailableMarket.json").getFile(),
CurrentMarket.class);
for example I have a json object like this:
{
"pic":"1.jpg",
"products":[
{
"id":1,
"pic":"4.jpg"
}
]
}
now I want to fetch all pic key inside an array or a list.
the result must be: ["1.jpg","4.jpg"]
There is a simple solution for this in jackson library.
String value = "{\"pic\":\"1.jpg\",\"products\":[{\"id\":1,\"pic\":\"4.jpg\"}]}";
JsonNode jsonNode = new ObjectMapper().readTree(value);
System.out.println(jsonNode.findValuesAsText("pic"));
You can add jackson by using following maven dependency.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
You can also pass file, inputstream to readTree().
Please try this code:
//define a list which will contain pic names
List<String> picList = new ArrayList<>();
try {
//jsonMap: your json object variable name
String picName = (String) jsonMap.get("pic");
picList.add(picName);
List<Map<String, Object>> products = (List<Map<String, Object>>) jsonMap.get("products");
for (Map<String, Object> product : products) {
String pic = (String) product.get("pic");
picList.add(pic);
}
System.out.println("=====List of pics===="+picList);
} catch (Exception e) {
}
It would be better if you parse the json to a POJO class. You can use Gson to convert json string to below Data class object.
String jsonString = "you json string here"
Data object = Gson().fromJson(jsonString, Data.class)
Now you have the object and can get product list from which you can iterate and get "pic" values.
Below is the class
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("pic")
#Expose
private String pic;
#SerializedName("products")
#Expose
private List<Product> products = null;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
-----------------------------------com.example.Product.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Product {
#SerializedName("id")
#Expose
private int id;
#SerializedName("pic")
#Expose
private String pic;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
If you want the list of pics within the products node, then you can get the entire JSON into a JSONObject, and iterate over the inner JSONArray
String str = "{\n" +
"\"pic\":\"1.jpg\",\n" +
"\"products\":[\n" +
"{\n" +
"\"id\":1,\n" +
"\"pic\":\"4.jpg\"\n" +
"}\n" +
"]\n" +
"\n" +
"}";
ArrayList<String> list = new ArrayList<>();
try {
JSONObject root = new JSONObject(str);
JSONArray products = root.getJSONArray("products");
for (int i = 0; i <= products.length(); i++) {
String value = ((JSONObject) products.get(i)).getString("pic");
list.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "onCreate: " + list);
My json string is:
{
"recordsTotal":1331,
"data":[
{
"part_number":"3DFN64G08VS8695 MS",
"part_type":"NAND Flash",
"id":1154,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DPM0168-2",
"part_type":"System in a Package (SiP)",
"id":452,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DSD1G16VS2620 SS",
"part_type":"SDRAM",
"id":269,
"manufacturers":[
"3D-Plus"
]
}
]
}
This code lets me access the two highest level elements:
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
System.out.println("data : " + jsonObject.get("data"));
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
But what I want to do is iterate over all the objects inside "data" and create a list of part_numbers. How do I do that?
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
#SerializedName("recordsTotal")
private Integer recordsTotal;
#SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
#SerializedName("part_number")
private String partNumber;
#SerializedName("part_type")
private String partType;
#SerializedName("id")
private Integer id;
#SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}
The given code will not guaranteed to 100% equivalent but it will help you to work.
First you have to create the class for your data objects:
class mydata {
public String part_name;
public String part_type;
public int Id;
public String manufacturers;
}
Your main method should look like
public static void main(String[] args) {
JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();
mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);
mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
}
For futher exploration you can use that link:
https://gist.github.com/codebutler/2339666
Im trying to create JsonObcject using code below
try {
JSONObject object = new JSONObject();
object.put("count", 39);
JSONArray results = new JSONArray();
JSONObject resultsAll = new JSONObject();
resultsAll.put("id", 2);
resultsAll.put("name", "PlaylistExample");
resultsAll.put("owned_by", 4);
resultsAll.put("votes_per_day", 25);
resultsAll.put("is_subscribed", true);
results.put(resultsAll);
object.put("results", results);
JSONArray finalArray = object.getJSONArray("results");
JSONObject finalObject = finalArray.getJSONObject(0);
result = new Results(finalObject);
} catch (JSONException e) {
e.printStackTrace();
}
But its not working, result is null, same with JsonObject. what am i doing wrong ?
EDIT. Results class with JsonProperties. Thats strange, im trying to create that JsonObcject as a mock for Test
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.json.JSONException;
import org.json.JSONObject;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Results {
#JsonProperty("id")
private int id;
#JsonProperty("name")
private String name;
#JsonProperty("owned_by")
private int owned_by;
#JsonProperty("votes_per_day")
private int votes_per_day;
#JsonProperty("tracks_to_play")
private int tracks_to_play;
#JsonProperty("is_subscribed")
private boolean is_subscribed;
public Results(JSONObject object) {
try {
this.id = object.getInt("id");
this.name = object.getString("name");
this.owned_by = object.getInt("owned_by");
this.votes_per_day = object.getInt("votes_per_day");
this.tracks_to_play = object.getInt("tracks_to_play");
this.is_subscribed = object.getBoolean("is_subscribed");
} catch (JSONException ex) {
ex.printStackTrace();
}
}
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 int getOwned_by() {
return owned_by;
}
public void setOwned_by(int owned_by) {
this.owned_by = owned_by;
}
public int getVotes_per_day() {
return votes_per_day;
}
public void setVotes_per_day(int votes_per_day) {
this.votes_per_day = votes_per_day;
}
public int getTracks_to_play() {
return tracks_to_play;
}
public void setTracks_to_play(int tracks_to_play) {
this.tracks_to_play = tracks_to_play;
}
public boolean is_subscribed() {
return is_subscribed;
}
public void setIs_subscribed(boolean is_subscribed) {
this.is_subscribed = is_subscribed;
}
}
The problem: I was trying to make that JsonObject within test
without testCompile 'org.json:json:20140107' its not possible.
I want to convert a JSONObject (array) to a list of Objects.
As I am very new with java i am having quite some problems.
JSON:
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
Product class:
public class Produkt {
public String id;
public String name;
public String categorie;
public String description;
public String image;
public double price;
}
I have tried several things with gson, but ultimately nothing worked.
I don't need a working code, just a hint on how to deserialize the JSON by the tags.
I hope you can help me. Thanks in advance!
Considering that your request or string data is in JSONObject jsonArray. Below code can help you get the response in List using TypeToken.
JSONArray jsonArray = jsonResponse.getJSONArray("products");
String newList = jsonArray.toString();
Gson gson = new Gson();
Type typeOfProduktList = new TypeToken<ArrayList<Produkt>>() {}.getType();
List<Produkt> finalList = gson.fromJson(newList, typeOfProduktList);
Now, you can return the finalList in the end or process it as per your wish.
Try creating a class that has a list of products. Here is a complete example:
Add brackets around your json data like this:
{
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
}
]
}
Here are the classes you need:
Data class:
public class Data {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Product class:
public class Product {
private String pid;
private String name;
private String kategorie;
private String beschreigung;
private String bild;
private String preis;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKategorie() {
return kategorie;
}
public void setKategorie(String kategorie) {
this.kategorie = kategorie;
}
public String getBeschreigung() {
return beschreigung;
}
public void setBeschreigung(String beschreigung) {
this.beschreigung = beschreigung;
}
public String getBild() {
return bild;
}
public void setBild(String bild) {
this.bild = bild;
}
public String getPreis() {
return preis;
}
public void setPreis(String preis) {
this.preis = preis;
}
}
GsonTest class:
public class GsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Object obj;
try {
JsonParser parser = new JsonParser();
obj = parser.parse(new FileReader("C:\data.json"));
JsonObject jsonObject = (JsonObject) obj;
Data data = gson.fromJson(jsonObject, Data.class);
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}