After parsing a nested JSON array with Gson, I now need to insert the result into SQLite. I tried inserting as done when not parsing with Gson, but that didn't work. I looked for ways to do that but couldn't find a solution.
The JSON parsing:
Gson gson = new Gson();
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countriesList = gson.fromJson(jsonString, listType);
for(Country country : countriesList) {
ContentValues insertValues;
}
If I wasn't using Gson, I would have written the line:
JSONObject countryObject = countriesList.getJSONObject(country);
EDIT
One of the objects from the JSON
[
{
"name":"Afghanistan",
"topLevelDomain":[
".af"
],
"callingCodes":[
"93"
],
"capital":"Kabul",
"region":"Asia",
"subregion":"Southern Asia",
"population":27657145,
"latlng":[
33.0,
65.0
],
"demonym":"Afghan",
"area":652230.0,
"gini":27.8,
"timezones":[
"UTC+04:30"
],
"nativeName":"افغانستان",
"numericCode":"004",
"currencies":[
{
"name":"Afghan afghani",
"symbol":"؋"
}
],
"languages":[
{
"name":"Pashto",
"nativeName":"پښتو"
},
{
"name":"Uzbek",
"nativeName":"Oʻzbek"
},
{
"name":"Turkmen",
"nativeName":"Türkmen"
}
],
"translations":{
"de":"Afghanistan",
},
"flag":"https://restcountries.eu/data/afg.svg",
"cioc":"AFG"
},
The model classes I wrote are only for the variables objects and arrays I needed.
The model class Country.Java
public class Country implements Parcelable {
private String name;
private String capital;
private String region;
private String subregion;
private int population;
private List<Double> latlng = new ArrayList<Double>();
private double area;
private double gini;
private List<String> timezones = new ArrayList<String>();
private List<Currency> currencies = new ArrayList<Currency>();
private List<Language> languages = new ArrayList<Language>();
private String flag;
public Country() {}
//getters, setters, toString() and Parcelable methods
}
The model class Currency.Java
public class Currency implements Parcelable {
private String name;
private String symbol;
//getters, setters, toString() and Parcelable methods
}
The model class Language.Java
public class Language implements Parcelable {
private String name;
private String nativeName;
//getters, setters, toString() and Parcelable methods
}
First get property of Country and then put it to content values and insert.
List<Country> countries = gson.fromJson(jsonString, new TypeToken<List<Country>>(){}.getType());
for(Country country : countries) {
String name = country.getName();
String capital = country.getCapital();
String region = country.getRegion();
String currencies = gson.toJson(country.getCurrencies());
...
ContentValues insertValues = new ContentValues();
insertValues.put("name", name)
insertValues.put("capital", capital);
insertValues.put("region", region);
insertValues.put("currencies", currencies);
...
long res = db.insert(TABLE_NAME, null, insertValues);
}
It's hard to know where your problem is without more code. You are doing two different operations:
unmarshalling a json
persisting data in SQLite.
Unmarshalling json with Gson
Inside the for-loop, can you log each country to see that you are getting a valid object with all the fields set? It is very much possible that you need to create a factory yourself. Does Country have subtype that you need to register through RuntimeTypeAdapterFactory? Maybe something like
final RuntimeTypeAdapterFactory<City> typeFactory = RuntimeTypeAdapterFactory
of(City.class, "MyCity")
.registerSubtype(S...,...)
Save in SQLite
Once you have valid data, then you must convert per field like so
public static ContentValues getContentValues(Country country) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, country.getId());
values.put(COLUMN_NAME, country.getName());
...
return values;
}
And then, if it still doesn't work, you will need to look at your SQLite schema.
Related
Edit
I managed to insert only the outer JSON object. Couldn't find information on how to insert nested objects. Each object has primitive fields in it. These objects can be seen in the JSON sample below: "languages" and "currencies". I also wonder how to deal with the "latlng" array within the outer JSON object, but it's probably better to handle these issues one at a time.
The code I got for inserting a primitive value in the outer JSON object:
Gson gson = new Gson();
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countriesList = gson.fromJson(jsonString, listType);
for(Country country : countriesList) {
ContentValues insertValues = new ContentValues();
insertValues.put(Country.NAME, country.getName());
//more insertions
}
The original question
I parsed a nested JSON with GSON (probably incorrectly since it's my first time). Now I'm trying to insert it to SQLite. Couldn't find what needs to be written next. When I write the for loop for the insertion I get the error cannot find symbol class Country. Couldn't find relevant guidance online so I hope anyone can help in how to move forward.
That's where the issue begins:
Country[] countriesArray = gson.fromJson(jsonString, Country[].class);
for (int i = 0; i < countriesArray.length(); i++) {
...
}
countriesArray.length() is marked as an error: cannot find symbol class Country.
One object from the JSON:
[
{
"name":"Afghanistan",
"topLevelDomain":[
".af"
],
"callingCodes":[
"93"
],
"capital":"Kabul",
"region":"Asia",
"subregion":"Southern Asia",
"population":27657145,
"latlng":[
33.0,
65.0
],
"demonym":"Afghan",
"area":652230.0,
"gini":27.8,
"timezones":[
"UTC+04:30"
],
"nativeName":"افغانستان",
"numericCode":"004",
"currencies":[
{
"name":"Afghan afghani",
"symbol":"؋"
}
],
"languages":[
{
"name":"Pashto",
"nativeName":"پښتو"
},
{
"name":"Uzbek",
"nativeName":"Oʻzbek"
},
{
"name":"Turkmen",
"nativeName":"Türkmen"
}
],
"translations":{
"de":"Afghanistan",
},
"flag":"https://restcountries.eu/data/afg.svg",
"cioc":"AFG"
},
The model classes I wrote are only for the variables objects and arrays I needed.
The model class Country.Java
public class Country implements Parcelable {
private String name;
private String capital;
private String region;
private String subregion;
private int population;
private List<Double> latlng = new ArrayList<Double>();
private double area;
private double gini;
private List<String> timezones = new ArrayList<String>();
private List<Currency> currencies = new ArrayList<Currency>();
private List<Language> languages = new ArrayList<Language>();
private String flag;
public Country() {}
//getters, setters, toString() and Parcelable methods
}
The model class Currency.Java
public class Currency implements Parcelable {
private String name;
private String symbol;
//getters, setters, toString() and Parcelable methods
}
The model class Language.Java
public class Language implements Parcelable {
private String name;
private String nativeName;
//getters, setters, toString() and Parcelable methods
}
Create a typeToken and pass it to fromJson method like following
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(jsonArray.toString(), listType);
Use Gson TypeToken to set the return object type during JSON parse
List<Country> countries = gson.fromJson(jsonString, new TypeToken<List<Country>>(){}.getType());
for(Country country : countries) {
//Do your DB operation here
}
I have a java.util.List<Student>; whereas Student is a simple class with few attributes like String name, String forName, int id, double averageCredtis;
As in this code:
class Student {
private String foreName;
private String surName;
private int id;
private double averageCredits;
public Student(String f, String n, int id, double aCred)
{
this.foreName = f;
this.surName = n;
this.id = id;
this. averageCredits = aCred;
}
}
Then I create multiple objects during runtime:
Student a = new Student("Alice", "Aaa", 123, 1.6);
Student b = new Student("Bob", "Bbb", 223, 1.0);
Student c = new Student("Chris", "Ccc", 457, 3.6);
I used to store them in a Lisdt by means of myList.add(a);.
I would like to generate a GSON String like:
{ "GlobalVal": "Value",
"GlobalNumber": "234",
"Student": {"Surname": "Aaa","Forename": "Alice", "id": 123, >"averageCredit": 1.7 }
"Student": {"Surname": "Bbb","Forename": "Bob", "id": >223,"averageCredit": 1.0 }
}
Create a class named Container
class Container{
String globalVal;
int globalInt;
List<Student> students;
}
Use GSON library to convert this to JSON. Create an instance of the above class and store the values.
Container obj = new Container();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
Use Gson lib to achieve the same.
Below link answers you question precisely.
Refer : http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
[{"a":
{"b":"c",
"d":"e",
"f":"g"}
{"a2":
{"b":"c2",
"d":"e2",
"f":"g2"}]
This is the JSON data I 'have to' use. Is there any easy way for me to reach, let's say the b values without having to go through a and a2?
Use GSON
You should create a class for that:
public class MyObject {
private A a;
private A a2;
// a and a2 getters here to check if it parses successfully
}
Class A
public class A {
private String b;
private String d;
private String f;
// getters
}
And somewhere where you want to parse:
Type listType = new TypeToken<ArrayList<MyObject >>() {}.getType();
Gson gson = new Gson();
List<MyObject> list = gson.fromJson(yourJsonStringHere, listType);
How can I parse this JSON using Gson?
I have an array with multiple object types and I don't know what kind of object I need to create to save this structure. I cannot change the json message (I don't control the server).
The only class that function (sort of) was this
public class Response {
private List<Object> tr;
private int results;
(...)
}
JSON Message (Note the array with multiple object types.)
{
"tr":
[
{
"a":
{
"userId": "112"
}
},
{
"b":
{
"userId": "123",
"address":"street dummy"
}
},
{
"a":
{
"userId": "154"
}
}
],
"results":3
}
The Gson User's Guide explicitly covers this:
https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types
You have an object with a field tr that is an array containing arbitrary types.
The users guide explains that you can't directly deserialize such a structure, and recomends:
Use Gson's parser API (low-level streaming parser or the DOM parser
JsonParser) to parse the array elements and then use Gson.fromJson()
on each of the array elements. This is the preferred approach.
In your case ... it would really depend on what objects were possible in that array. If they are all going to have that same inner object you'd want to do something like...
List<MyUserPojo> list = new ArrayList<MyUserPojo>();
JsonArray array = parser.parse(json).getAsJsonObject().getAsJsonArray("tr");
for (JsonElement je : array)
{
Set<Map.Entry<String,JsonElement>> set = je.getAsObject().entrySet();
JsonElement je2 = set.iterator().next().getValue();
MyUserPojo mup = new Gson().fromJson(je2, MyUserPojo.class);
list.add(mup);
}
And of course, this would need to be inside a custom deserializer for your actual object that would have the tr and results fields.
class MyPojo
{
List<MyUserPojo> userList;
int results;
}
class MyUserPojo
{
String userId;
String address;
}
class MyDeserializer implements JsonDeserializer<MyPojo>
{
#Override
public MyPojo deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
List<MyUserPojo> list = new ArrayList<MyUserPojo>();
JsonArray array = je.getAsJsonObject().getAsJsonArray("tr");
for (JsonElement je2 : array)
{
Set<Map.Entry<String,JsonElement>> set = je2.getAsObject().entrySet();
JsonElement je3 = set.iterator().next().getValue();
MyUserPojo mup = new Gson().fromJson(je3, MyUserPojo.class);
list.add(mup);
}
MyPojo mp = new MyPojo();
mp.tr = list;
mp.results = je.getAsObject().getAsJsonPrimitive("results").getAsInt();
return mp;
}
}
Now you're all set - you can use that deserializer and create your object:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyPojo.class, new MyDeserializer())
.build();
MyPojo mp = gson.fromJson(json, MyPojo.class);
If the a, b etc are important ... well, you'll have to figure that out. But the above should get you well on your way to understanding what's going to be needed to deal with your JSON structure.
For completeness sake, the only "hacky" way around this is if there is a fairly limited number of those types and the inner object also is fairly limited in terms of its fields. You could create a POJO that encompasses all the possibilities:
class MyPojo
{
MySecondPojo a;
MySecondPojo b;
...
MySecondPojo f;
}
class MySecondPojo
{
String userId;
String address;
...
String someOtherField;
}
When Gson deserializes JSON it will set any missing fields in your POJO(s) to null. You could now have tr be a List or array of these in your POJO. Again and to emphasize, this is really quite hacky and the wrong way to do it, but I thought I'd explain what would be required to directly parse that array.
I pick something from each answer and did it this way:
Response Object
public class Response {
private List<Users> tr;
private int results;
(...)
}
Generic User
public class User {
public static final int TYPE_USER_A =0;
public static final int TYPE_USER_B =1;
private String userId;
private int type;
(...)
}
A
public class a extends User {
private String location;
(...)
}
B
public class b extends User {
private String adress;
(...)
}
Parsing Method
private Response buildResponseObject(String response) {
Response tls = new Response();
List<Users> users = new ArrayList<users>();
User u;
try {
JSONObject object = new JSONObject(response);
tls.setResults(object.getInt("results"));
JSONArray array = object.getJSONArray("tr");
for (int i = 0; i < array.length(); i++) {
JSONObject trs = array.getJSONObject(i);
if (trs.has("a")) {
String json = trns.getString("a");
A a = new Gson().fromJson(json,A.class);
a.setType(User.TYPE_USER_A);
users.add(a);
} else if (trs.has("b")) {
String json = trs.getString("b");
B b= new Gson().fromJson(json,B.class);
B.setType(User.TYPE_USER_B);
users.add(b);
}
}
tls.setUsers(users);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tls;
}
This is not as elegant as I wanted and mix native JsonObjects with Gson methods but works for me.
Try this code here:
public class Address {
public String userId;
public String address;
// ...
}
public class Response {
private HashMap<String, Address> tr;
private int results;
// ...
}
Usage:
String json = "{\n \"tr\":\n {\n \"a\": {\n \"userId\": \"112\"\n },\n \"b\": {\n \"userId\": \"123\",\n \"address\":\"street dummy\"\n },\n \"c\": {\n \"userId\": \"154\"\n }\n },\n \"results\":3\n}";
Response users = new Gson().fromJson(json, Response.class);
As you may see I needed to modify the structure:
{
"tr":
{
"a": {
"userId": "112"
},
"b": {
"userId": "123",
"address":"street dummy"
},
"c": {
"userId": "154"
}
},
"results":3
}
But unfortunately I don't get it managed to allow multiple keys. Right now I have no idea how to fix this.
I think this link might help you:
https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples
Basically, create a class for your "object" (kind of user I guess), and then use the deserialization code of Gson, like this:
Type collectionType = new TypeToken<Collection<User>>(){}.getType();
Collection<User> users= gson.fromJson(json, collectionType);
You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html
I use ormlite and I have a db with a field:
public static final String NAME = "name";
#DatabaseField (canBeNull = false, dataType = DataType.SERIALIZABLE, columnName = NAME)
private String[] name = new String[2];
And I would like to get all elements that name[0] and name[1] are "car". I try to add a where clausule like:
NAMEDB nameDB = null;
Dao<NAMEDB, Integer> daoName = this.getHelper().getDao(NAMEDB.class);
QueryBuilder<NAMEDB, Integer> queryName = daoName.queryBuilder();
Where<NAMEDB, Integer> where = queryName.where();
where.in(nameDb.NAME, "car");
But it doesn't work because it's an array string.
I have other fields:
public static final String MARK = "mark";
#DatabaseField (canBeNull = false, foreign = true, index = true, columnName = MARK)
private String mark = null;
And I can do this:
whereArticulo.in(nameDB.MARK, "aaa");
How can I solve my problem? Thanks.
It seems to me that a third option to store a string array (String[] someStringArray[]) in the database using Ormlite would be to define a data persister class that converts the string array to a single delimited string upon storage into the database and back again to a string array after taking it out of the database.
E.g., persister class would convert ["John Doe", "Joe Smith"] to "John Doe | Joe Smith" for database storage (using whatever delimiter character makes sense for your data) and converts back the other way when taking the data out of the database.
Any thoughts on this approach versus using Serializable or a foreign collection? Anyone tried this?
I just wrote my first persister class and it was pretty easy. I haven't been able to identify through web search or StackOverflow search that anyone has tried this.
Thanks.
As ronbo4610 suggested, it is a good idea to use a custom data persister in this case, to store the array as a string in the database separated by some kind of delimiter. You can then search the string in your WHERE clause just as you would any other string. (For example, using the LIKE operator)
I have implemented such a data persister. In order to use it, you must add the following annotation above your String[] object in your persisted class:
#DatabaseField(persisterClass = ArrayPersister.class)
In addition, you must create a new class called "ArrayPersister" with the following code:
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.field.types.StringType;
import org.apache.commons.lang3.StringUtils;
public class ArrayPersister extends StringType {
private static final String delimiter = ",";
private static final ArrayPersister singleTon = new ArrayPersister();
private ArrayPersister() {
super(SqlType.STRING, new Class<?>[]{ String[].class });
}
public static ArrayPersister getSingleton() {
return singleTon;
}
#Override
public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
String[] array = (String[]) javaObject;
if (array == null) {
return null;
}
else {
return StringUtils.join(array, delimiter);
}
}
#Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
String string = (String)sqlArg;
if (string == null) {
return null;
}
else {
return string.split(delimiter);
}
}
}
Unfortunately ORMLite does not support querying fields that are the type SERIALIZABLE. It is storing the array as a serialized byte[] so you cannot query against the values with an IN query like:
where.in(nameDb.NAME, "car");
ORMLite does support foreign collections but you have to set it up yourself with another class holding the names. See the documentation with sample code:
http://ormlite.com/docs/foreign-collection