Reputation: 140
I've seen a lot of similar questions. I haven't been able to find any that fit my exact issue. In all of the examples I've found the List is of an object type defined in the parent class, whereas I just have a list of Strings. I've tried using a simple array String[], and I've seen examples with overloading deserializers, and getting the TypeToken but I can't tie it together to make this work. My list is always empty (or null if I don't initialize it when I define the list). What am I missing here, it feels like I'm trying to do something very simple but everything I find on it looks overly complex.
This is my class:
public class MondoConfig {
private String merchantURL;
public ArrayList<String> targets = new ArrayList<String>();
public MondoConfig () {}
public String getMerchantURL() {
return this.merchantURL;
}
public void setMerchantURL(String url) {
this.merchantURL = url;
}
public ArrayList<String> getTargets() {
return this.targets;
}
public void setTargets(ArrayList<String> t) {
this.targets = t;
}
}
This is my json:
{
"merchantURL":"https://example.com/collections/posters",
"targets":[
"testing",
"another",
"one more"
]
}
And my code to deserialize:
BufferedReader br = new BufferedReader(new FileReader("C:\\mondo_config.json"));
MondoConfig config = gson.fromJson(br, MondoConfig.class);
Upvotes: 0
Views: 264
Reputation: 1756
I'm seeing a few problems in your code, but I was able to get it to work without any issues.
package org.nuttz.gsonTest;
import java.util.ArrayList;
public class MondoConfig {
private String merchantURL;
public ArrayList<String> targets = new ArrayList<String>();
MondoConfig () {}
public String getMerchantURL() {
return this.merchantURL;
}
public void setMerchantURL(String url) {
this.merchantURL = url;
}
public ArrayList<String> getTargets() {
return this.targets;
}
public void setTargets(ArrayList<String> t) {
this.targets = t;
}
}
The setMerchantURL() function in your original code wasn't quite right, so I fixed it. Then I used this code to test it:
package org.nuttz.gsonTest;
import java.io.*;
import java.util.List;
import com.google.gson.*;
public class App
{
public static void main( String[] args )
{
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("/home/jim/mondoconfig.json"));
MondoConfig config = gson.fromJson(br, MondoConfig.class);
System.out.println("Contents of config:");
System.out.println(config.getMerchantURL());
List<String> targets = config.targets;
for (String t : targets) {
System.out.println(t);
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
And got the following results:
Contents of config:
https://example.com/collections/posters
testing
another
one more
This is using the 2.8.2 version of GSON. In other words, you're on the right track, you've just need to fix the MondoConfig class.
Upvotes: 1