So I am trying to create this json file using gson - java

Here is the code I want to create with my Java code. I'm not doing anything elaborate. Just trying to refresh myself with parsing json from java.
[{"county":"Jefferson",
"houses":\[
{"squareFeet":1100,
"bedrooms":2,
"bathrooms":2,
"internet":"y",
"location":"Country"
},
{"squareFeet":750,
"bedrooms":1,
"bathrooms":1,
"internet":"n",
"location":"Town"
}
\]
}]
At the moment my Java code looks like this.
With this code below I am close to having it, with the exception of the first Object, and also the title to the array of houses.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
public class HousesToJSON {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JSONArray houses = new JSONArray();
House houseOne = createHouseObjectOne();
House houseTwo = createHouseObjectTwo();
houses.add(houseOne);
houses.add(houseTwo);
try (FileWriter writer = new FileWriter("houses.json")) {
gson.toJson(houses, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
private static House createHouseObjectOne() {
House house = new House();
house.setSquareFeet(1100);
house.setBedrooms(2);
house.setBathrooms(2);
house.setInternet('y');
house.setLocation("Country");
return house;
}
private static House createHouseObjectTwo() {
House house = new House();
house.setSquareFeet(750);
house.setBedrooms(2);
house.setBathrooms(1);
house.setInternet('y');
house.setLocation("Town");
return house;
}
}
This create the file below.
[
{
"squareFeet": 1100,
"bedrooms": 2,
"bathrooms": 2,
"internet": "y",
"location": "Country"
},
{
"squareFeet": 750,
"bedrooms": 2,
"bathrooms": 1,
"internet": "y",
"location": "Town"
}
]
I am still pretty new at this, and any help would be much appreciated.

Something along the lines of this should provide you with the neccesary objects for your JSON example:
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CountyContainer {
#SerializedName("county")
#Expose
private String county;
#SerializedName("houses")
#Expose
private List<House> houses = null;
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public List<House> getHouses() {
return houses;
}
public void setHouses(List<House> houses) {
this.houses = houses;
}
}
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class House {
#SerializedName("squareFeet")
#Expose
private Integer squareFeet;
#SerializedName("bedrooms")
#Expose
private Integer bedrooms;
#SerializedName("bathrooms")
#Expose
private Integer bathrooms;
#SerializedName("internet")
#Expose
private String internet;
#SerializedName("location")
#Expose
private String location;
public Integer getSquareFeet() {
return squareFeet;
}
public void setSquareFeet(Integer squareFeet) {
this.squareFeet = squareFeet;
}
public Integer getBedrooms() {
return bedrooms;
}
public void setBedrooms(Integer bedrooms) {
this.bedrooms = bedrooms;
}
public Integer getBathrooms() {
return bathrooms;
}
public void setBathrooms(Integer bathrooms) {
this.bathrooms = bathrooms;
}
public String getInternet() {
return internet;
}
public void setInternet(String internet) {
this.internet = internet;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
You can generate these yourself using this online service and selecting the GSON annotation style:
http://www.jsonschema2pojo.org/
When you've created your objects, you can write those objects to a JSON file using:
final Gson gson = new Gson();
try (final FileWriter writer = new FileWriter("houses.json")) {
gson.toJson(houses, writer); // houses refers to your object containing the List of House objects and the country
} catch (final IOException e) {
// Handle exceptions here
}
Alternatively, you can also use place the JSON data into a String:
String json = gson.toJson(houses);
For more information regarding GSON functionality, please take a look at the official documentation:
https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/module-summary.html

There is no House class provided, but I guess we can skip it. You are moving in the right direction. Just add another class:
public class County {
private String county;
private List<House> houses;
// getters, setters, whatever :)
}
And create instance of this class. Set name (county field) and houses and serialize to JSON :)
I would probably rename json array to JSONArray counties = new JSONArray(); and what you need to add to this array is some county with name "Jefferson" and list of houses that you have now.
County county = new County();
county.setCounty("Jefferson");
List<House> houses = new ArrayList<>();
houses.add(houseOne);
houses.add(houseTwo);
county.setHouses(houses);
counties.add(county);
This might not be 100% working code, but hope the idea is clear :)

Related

How to iterate through an Json array with same keys, but different values using Faster xml

I am trying to parse the json array with same key value which looks something like:
Back End Response:"Countries":[{"state":"Queens Land "state":"Tasmania"}].
2.I have created classes to read back end response and mapping the values with faster XML, but only the last value in the array is getting copied, instead of entire array. This is how I created my Data Transfer Object classes.
Now the Test object contains Countries array, but only one of the State value is read. i.e
"Countries":["States":"Tasmania"].
Please excuse me for typos. can some one help, can some one suggest whats wrong with the bellow code..
private Class Test{
List<Countries> countries;
}
private class Countries{
private String States;
}
private class Mapper {
}
In my Mapper class reading the value using faster XML
Assume that your JSON payload is:
{
"Countries": [
{
"state": "Queens Land",
"state": "Tasmania"
}
]
}
According to RFC7159:
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
In your example, you have not unique names and most JSON parsers would skip repeated values and would take only one. So, if you can change backend response, just change it to:
{
"Countries": [
{
"state": "Queens Land"
},
{
"state": "Tasmania"
}
]
}
or
{
"Countries": [
"Queens Land",
"Tasmania"
]
}
But if you can not do that, you need to use Streaming API and implement your custom deserialiser. See below example:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
Test test = mapper.readValue(jsonFile, Test.class);
System.out.println(test);
}
}
class CountriesJsonDeserializer extends JsonDeserializer<Countries> {
#Override
public Countries deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
List<String> states = new ArrayList<>();
while (p.nextToken() != JsonToken.END_OBJECT) {
if (p.currentToken() == JsonToken.FIELD_NAME) {
if ("state".equalsIgnoreCase(p.getText())) {
p.nextToken();
states.add(p.getText());
}
}
}
Countries countries = new Countries();
countries.setStates(states);
return countries;
}
}
class Test {
#JsonProperty("Countries")
private List<Countries> countries;
public List<Countries> getCountries() {
return countries;
}
public void setCountries(List<Countries> countries) {
this.countries = countries;
}
#Override
public String toString() {
return "Test{" +
"countries=" + countries +
'}';
}
}
#JsonDeserialize(using = CountriesJsonDeserializer.class)
class Countries {
private List<String> states;
public List<String> getStates() {
return states;
}
public void setStates(List<String> states) {
this.states = states;
}
#Override
public String toString() {
return "Countries{" +
"states=" + states +
'}';
}
}
Above example prints:
Test{countries=[Countries{states=[Queens Land, Tasmania]}]}
See also:
Intro to the Jackson ObjectMapper

Two differents types of responses in POJO

I'm using Retrofit with POJO, which usually works, but the answer has two different objects depending on whether the result is valid. Which one is a String and the another is an Object:
{
"data":"No results."
}
or:
{
"data": {
"exame": [
{
"id": 776,
"codigo": "DHT",
"instrucao": "- Text."
},
{
"id": 776,
"codigo": "DHT",
"instrucao": "- Text"
}
]
}
}
And my class:
public class Exame {
#SerializedName("data")
#Expose
#Nullable
private ExameItem exameItem;
private String mensagem;
public ExameItem getExameItem() {
return exameItem;
}
public void setExameItem(ExameItem exameItem) {
this.exameItem = exameItem;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
}
When I do Exame().getExameItem its fine, but when I try test if have a message in Exame().getMessagem its bring me a this error:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 10 path $.data
So, I think how can I test if #data is a String of an Object, but I don't kwon how, anyone may help?
You need to implement custom deserialiser by implementing JsonDeserializer interface. See below example:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().create();
System.out.println(gson.fromJson(new FileReader(jsonFile), Exame.class));
}
}
class ExamsJsonDeserializer implements JsonDeserializer<Exame> {
#Override
public Exame deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject root = json.getAsJsonObject();
JsonElement data = root.get("data");
Exame exam = new Exame();
if (data.isJsonPrimitive()) {
exam.setMensagem(data.getAsString());
} else {
ExameItem examItem = context.deserialize(data, ExameItem.class);
exam.setExameItem(examItem);
}
return exam;
}
}
#JsonAdapter(ExamsJsonDeserializer.class)
class Exame {
private ExameItem exameItem;
private String mensagem;
// getters, setters, toString
}
class ExameItem {
private List<Item> exame;
//getters, setters, toString
}
class Item {
private int id;
// ...
//getters, setters, toString
}

Serialization/Deserialization JSON Jackson HashMap JAVA

I have a simple problem, but I cannot find a solution by myself.
I need serialize two maps. One has Object as key and Integer as value. Another One has similar properties but key-object contains a list.
Here are my models.
Detail
package Model;
/**
* Created by kh0ma on 01.11.16.
*/
public class Detail {
private String name;
public Detail() {
}
public Detail(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Detail{" +
"name='" + name + '\'' +
'}';
}
}
Mechanism
package Model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kh0ma on 01.11.16.
*/
public class Mechanism {
private String name;
private List<Detail> details;
public Mechanism(String name) {
this.name = name;
this.details = new ArrayList<Detail>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
#Override
public String toString() {
return "Mechanism{" +
"name='" + name + '\'' +
", details=" + details +
'}';
}
}
Then I pull data in maps by another class.
PullData
package PullData;
import Model.Detail;
import Model.Mechanism;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kh0ma on 01.11.16.
*/
public class PullData {
public static Map<Detail,Integer> DETAILS = new HashMap<Detail, Integer>();
public static Map<Mechanism,Integer> MECHANISMS = new HashMap<Mechanism, Integer>();
private static Detail detail1 = new Detail("Wheel");
private static Detail detail2 = new Detail("Frame");
private static Detail detail3 = new Detail("Seat");
private static Detail detail4 = new Detail("Engine");
private static Detail detail5 = new Detail("Headlight");
public static void pullDetails()
{
DETAILS.put(detail1,6);
DETAILS.put(detail2,2);
DETAILS.put(detail3,5);
DETAILS.put(detail4,1);
DETAILS.put(detail5,2);
}
public static void pullMechanisms()
{
Mechanism car = new Mechanism("Car");
car.getDetails().add(detail1);
car.getDetails().add(detail2);
car.getDetails().add(detail3);
car.getDetails().add(detail4);
car.getDetails().add(detail5);
Mechanism bicycle = new Mechanism("Bicycle");
bicycle.getDetails().add(detail1);
bicycle.getDetails().add(detail2);
MECHANISMS.put(car,1);
MECHANISMS.put(bicycle,1);
}
}
Than I try to serialize and deserialize maps in main method.
TestJSON
package TestJSON;
import Model.Detail;
import Model.Mechanism;
import PullData.PullData;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kh0ma on 01.11.16.
*/
public class TestJSON {
public static void main(String[] args) {
PullData.pullDetails();
PullData.pullMechanisms();
System.out.println("=+=+=+=BEFORE JSON SERIALISATION=+=+=+=");
System.out.println("-=-=-=-=-=Before changes=-=-=-=-=-=-");
PullData.DETAILS.forEach((k, v) -> System.out.println(k));
PullData.MECHANISMS.forEach((k, v) -> System.out.println(k));
System.out.println("-=-=-=-=-=After changes=-=-=-=-=-=-");
PullData.MECHANISMS.forEach((k, v) -> {
if (k.getName().equals("Bicycle")) k.getDetails()
.forEach((detail -> detail.setName(detail.getName() + "FirstChanges")));
});
PullData.DETAILS.forEach((k, v) -> System.out.println(k));
PullData.MECHANISMS.forEach((k, v) -> System.out.println(k));
System.out.println("=+=+=+=JSON Print=+=+=+=");
ObjectMapper objectMapper = new ObjectMapper();
File jsonFileDetails = new File("src/main/resources/json/jsonDetails.txt");
File jsonFileMechanisms = new File("src/main/resources/json/jsonMechanisms.txt");
try {
objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFileDetails, PullData.DETAILS);
objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFileMechanisms, PullData.MECHANISMS);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=+=+=+=AFTER JSON SERIALISATION=+=+=+=");
System.out.println("-=-=-=-=-=Before changes=-=-=-=-=-=-");
ObjectMapper mapper = new ObjectMapper();
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, Mechanism.class, Integer.class);
Map<Detail, Integer> detailesAfterJson = new HashMap<Detail, Integer>();
Map<Mechanism, Integer> mechanismsAfterJson = new HashMap<Mechanism, Integer>();
try {
detailesAfterJson = mapper.readValue(jsonFileDetails, new TypeReference<HashMap<Detail, Integer>>() {});
mechanismsAfterJson = mapper.readValue(jsonFileMechanisms, new TypeReference<Map<Mechanism, Integer>>() {});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
detailesAfterJson.forEach((k, v) -> System.out.println(k));
mechanismsAfterJson.forEach((k, v) -> System.out.println(k));
}
}
First map serializes like this.
jsonDetails.txt
{
"Detail{name='WheelFirstChanges'}" : 6,
"Detail{name='FrameFirstChanges'}" : 2,
"Detail{name='Seat'}" : 5,
"Detail{name='Engine'}" : 1,
"Detail{name='Headlight'}" : 2
}
And another one like this.
jsonMechanisms.txt
{
"Mechanism{name='Car', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}, Detail{name='Seat'}, Detail{name='Engine'}, Detail{name='Headlight'}]}" : 1,
"Mechanism{name='Bicycle', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}]}" : 1
}
In java console I have this output.
console_output
/usr/lib/jvm/jdk1.8.0_102/bin/java -Didea.launcher.port=7544 -Didea.launcher.bin.path=/home/kh0ma/idea-IU-162.1121.32/bin -Dfile.encoding=UTF-8 -classpath "/usr/lib/jvm/jdk1.8.0_102/jre/lib/charsets.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/deploy.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/dnsns.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/jaccess.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/localedata.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/nashorn.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/sunec.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/ext/zipfs.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/javaws.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/jce.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/jfr.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/jfxswt.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/jsse.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/management-agent.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/plugin.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/resources.jar:/usr/lib/jvm/jdk1.8.0_102/jre/lib/rt.jar:/home/kh0ma/Dropbox/JavaStuding/JavaRush/JavaRushHomeWork/Test JSON for ANTONIOPRIME/target/classes:/home/kh0ma/Dropbox/JavaStuding/JavaRush/JavaRushHomeWork/Test JSON for ANTONIOPRIME/lib/gson-2.7.jar:/home/kh0ma/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.2.3/jackson-databind-2.2.3.jar:/home/kh0ma/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.2.3/jackson-annotations-2.2.3.jar:/home/kh0ma/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.2.3/jackson-core-2.2.3.jar:/home/kh0ma/idea-IU-162.1121.32/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain TestJSON.TestJSON
=+=+=+=BEFORE JSON SERIALISATION=+=+=+=
-=-=-=-=-=Before changes=-=-=-=-=-=-
Detail{name='Wheel'}
Detail{name='Frame'}
Detail{name='Seat'}
Detail{name='Engine'}
Detail{name='Headlight'}
Mechanism{name='Car', details=[Detail{name='Wheel'}, Detail{name='Frame'}, Detail{name='Seat'}, Detail{name='Engine'}, Detail{name='Headlight'}]}
Mechanism{name='Bicycle', details=[Detail{name='Wheel'}, Detail{name='Frame'}]}
-=-=-=-=-=After changes=-=-=-=-=-=-
Detail{name='WheelFirstChanges'}
Detail{name='FrameFirstChanges'}
Detail{name='Seat'}
Detail{name='Engine'}
Detail{name='Headlight'}
Mechanism{name='Car', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}, Detail{name='Seat'}, Detail{name='Engine'}, Detail{name='Headlight'}]}
Mechanism{name='Bicycle', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}]}
=+=+=+=JSON Print=+=+=+=
=+=+=+=AFTER JSON SERIALISATION=+=+=+=
-=-=-=-=-=Before changes=-=-=-=-=-=-
Detail{name='Detail{name='Engine'}'}
Detail{name='Detail{name='Seat'}'}
Detail{name='Detail{name='Headlight'}'}
Detail{name='Detail{name='WheelFirstChanges'}'}
Detail{name='Detail{name='FrameFirstChanges'}'}
Mechanism{name='Mechanism{name='Bicycle', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}]}', details=[]}
Mechanism{name='Mechanism{name='Car', details=[Detail{name='WheelFirstChanges'}, Detail{name='FrameFirstChanges'}, Detail{name='Seat'}, Detail{name='Engine'}, Detail{name='Headlight'}]}', details=[]}
Process finished with exit code 0
As you can see the maps before and after have differences, but I need absolutely identical maps.
Can you suggest me the solution?
I downloaded clases into GitHub repository.
JSON_TEST
Thanks for your answers.
In JSON, keys must be strings. Your implementation uses the toString methods of Detail and Mechanism as keys. Since these methods return different strings, the JSON keys will be different.
I recommend to not use anything else than strings as map keys if you want to serialize to JSON.

IllegalStateException: This is not a JSON Array (Gson Java)

I've been trying to create using Gson a way to import track data. This is my first attempt at using Gson and I am struggling to understand where I am going wrong. I am trying to use spotify's json. This is the address I am using.
https://api.spotify.com/v1/search?q=%22Perform%20this%20way%22&type=track
And I've created a class to import it. I have been following this guide.
http://www.javabeat.net/invoking-restful-web-service-using-api-in-java-net-and-gson/
I get the following error after typing in my query and giving it the okay to go ahead..
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at TestingNonApplication.GsonTesting.main2(GsonTesting.java:72)
- Refers to this line. JsonArray jArray = rootElement.getAsJsonArray();
Is there anything I've left out. I wasn't sure if I needed a toString or serialization.
package TestingNonApplication;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Scorchgid
*/
public class GsonTesting {
/**
* #param args the command line arguments
*/
String baseURLStart = "http://api.spotify.com/v1/search?q=\"";
String baseURLEnd = "\"&type=track";
String jsonSource;
public static void main(String[] args) {
try {
GsonTesting gTest = new GsonTesting();
gTest.main2();
} catch (FileNotFoundException ex) {
Logger.getLogger(GsonTesting.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GsonTesting.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void main2() throws FileNotFoundException, MalformedURLException, IOException {
Scanner commandlineReader = new Scanner(System.in);
String searchString = "";
boolean contin = false;
while (contin == false) {
System.out.println("Enter query");
String query = commandlineReader.nextLine();
searchString = baseURLStart + query + baseURLEnd;
searchString = searchString.replace(" ", "%20");
System.out.println(searchString
+ "\r\n Type Yes to continue or anything else to re enter");
query = commandlineReader.nextLine();
if (query.equalsIgnoreCase("yes")) {
contin = true;
}
}
//----------------------------------------------------------------------
/* Connection and Response */
URLConnection urlConnection = new URL(searchString).openConnection();
urlConnection.connect();
JsonReader reader = new JsonReader(new InputStreamReader(urlConnection.getInputStream()));
JsonParser jsonParser = new JsonParser();
JsonElement rootElement = jsonParser.parse(reader);
JsonArray jArray = rootElement.getAsJsonArray();
List results = new ArrayList();
Gson gson = new Gson();
for (JsonElement spotifyElement : jArray) {
Tracks spot = gson.fromJson(rootElement, Tracks.class);
results.add(spot);
System.out.println(spot.toString());
}
}
}
class Tracks {
String href;
List<Items> items;
public class Items {
Album albums;
public class Album {
String album_type;
String[] available_markets;
External_Urls external_urls;
public class External_Urls {
String spotify;
}
String href;
String id;
List<Image> images;
public class Image {
Integer height;
String url;
Integer width;
}
String name;
String type;
String uri;
List<Artists> artists;
}
List<Artists> artist;
public class Artists {
External_Urls external_urls;
public class External_Urls {
String spotify;
}
String herf;
String id;
String name;
String type;
String uri;
}
String avaliable_markets;
Integer disc_number;
Integer duration;
Boolean explicity;
External_Urls external_ids;
public class External_Ids {
String isrc;
}
External_Urls external_urls;
public class External_Urls {
String spotify;
}
String herf;
String id;
String name;
Integer popularity;
String preview_url;
Integer tracknumber;
String type;
String uri;
}
Integer limit;
String next;
Integer offset;
String previous;
Integer total;
}
Json string is perfect.
There are 4 mistakes in your class to map json to obj. (class Tracks)
external_urls should be an object, not list (at all three places)
artists list should be outside album class.
external_ids should be object, not list (at one place)
spotify member is missing in one external_urls class.
A general advise is to reduce the use of inner classes when using gson (convert your inner classes to normal public classes and create the object instead of the inner class).
Also more readable and reusable code in this case. For example, if you design your external_urls as a separate class you just need one class and can have 3 member obj instead of the 3 inner classes you have now. Gson will work perfectly if you do so.

How do I add nested json Objects to file using Gson?

So I have the following code:
Team team = new Team();
team.setLeader(player.getUniqueId().toString());
team.setTeamName(args[1]);
team.setSerilizedInventory(InventoryStringDeSerializer.InventoryToString(inventory));
List<String> mods = new ArrayList<String>();
team.setMods(mods);
team.setMembers(members);
Teams teams = new Teams();
teams.setTeam(team);
try{
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Writer writer = new FileWriter(instance.getFile());
gson.toJson(team, writer);
writer.close();
}catch(IOException e){
e.printStackTrace();
}
I am attempting to create a json file that contains all my team values, but I am not sure how to make it in nested object forum.
I am wanting to follow this json structer.
{
"teams",{
"teamname",{
"members":["069dcc56-cc5b-3867-a4cd-8c00ca516344"],
"leader": "RenegadeEagle",
"serilizedInventory": "54;",
"mods":[],
leader: "069dcc56-cc5b-3867-a4cd-8c00ca516344",
}
}
}
That may not even be proper Json but you get the idea. So how would I write this using gson to a file?
Thanks.
Please check this solution, you need to have reference in multiple levels
For writing file to the Android file system refer this link for solution
Error: Could not find or load main class com.example.pdfone.MainActivity
However i strongly recommend you to store this JSON in a SQL Lite Table.
Team.java
import java.util.List;
public class Team {
private String leader;
private String serilizedInventory;
private List members;
private List mods;
public String getLeader() {
return leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
public String getSerilizedInventory() {
return serilizedInventory;
}
public void setSerilizedInventory(String serilizedInventory) {
this.serilizedInventory = serilizedInventory;
}
public List getMembers() {
return members;
}
public void setMembers(List members) {
this.members = members;
}
public List getMods() {
return mods;
}
public void setMods(List mods) {
this.mods = mods;
}
}
TeamsWrapper.java
import java.util.List;
public class TeamsWrapper {
private List<Team> team;
private String teamName;
public List<Team> getTeam() {
return team;
}
public void setTeam(List<Team> team) {
this.team = team;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
Test.java --> Main Program
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Team team = new Team();
team.setLeader("RenegadeEagle");
team.setSerilizedInventory("54;");
team.setMods(new ArrayList());
List members = new ArrayList();
members.add("069dcc56-cc5b-3867-a4cd-8c00ca516344");
team.setMembers(members);
TeamsWrapper tw = new TeamsWrapper();
List ls1 = new ArrayList();
ls1.add(team);
ls1.add(team);
tw.setTeam(ls1);
tw.setTeamName("teamname");
Gson gson = new GsonBuilder().create();
System.out.println(gson.toJson(tw));
}
}
Final Output from the program
{
"team" : [{
"leader" : "RenegadeEagle",
"serilizedInventory" : "54;",
"members" : ["069dcc56-cc5b-3867-a4cd-8c00ca516344"],
"mods" : []
}, {
"leader" : "RenegadeEagle",
"serilizedInventory" : "54;",
"members" : ["069dcc56-cc5b-3867-a4cd-8c00ca516344"],
"mods" : []
}
],
"teamName" : "teamname"
}

Categories

Resources