There's a few topics like this, however I've read them all and still no luck.
I have a class to which I've made to deserialize some JSON responses from a web service. In short, I've spent too much time looking at this and I'm hoping someone can pick out the error of my ways. As per title, I'm using the Jackson libs.
Snippet of the class below:
final class ContentManagerResponse implements Serializable {
#JsonProperty("Results")
private List<OrgSearchResult> results = null;
#JsonProperty("PropertiesAndFields")
private PropertiesAndFields propertiesAndFields;
#JsonProperty("TotalResults")
private Integer totalResults;
#JsonProperty("CountStringEx")
private String countStringEx;
#JsonProperty("MinimumCount")
private Integer minimumCount;
#JsonProperty("Count")
private Integer count;
#JsonProperty("HasMoreItems")
private Boolean hasMoreItems;
#JsonProperty("SearchTitle")
private String searchTitle;
#JsonProperty("HitHighlightString")
private String hitHighlightString;
#JsonProperty("TrimType")
private String trimType;
#JsonProperty("ResponseStatus")
private ResponseStatus responseStatus;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("Results")
public List<OrgSearchResult> getResults() {
return results;
}
#JsonProperty("Results")
public void setResults(List<OrgSearchResult> results) {
this.results = results;
}
//additional getters and setters.
As said, Results is the property which seems to be having the error.
The JSON response is below.
{
"Results": [
{
"TrimType": "Location",
"Uri": 1684
}
],
"PropertiesAndFields": {},
"TotalResults": 1,
"CountStringEx": "1 Location",
"MinimumCount": 1,
"Count": 0,
"HasMoreItems": false,
"SearchTitle": "Locations - type:Organization and id:24221",
"HitHighlightString": "",
"TrimType": "Location",
"ResponseStatus": {}
}
I'm using the same class to deserialize the following response and it works:
{
"Results": [
{
"LocationIsWithin": {
"Value": true
},
"LocationSortName": {
"Value": "GW_POS_3"
},
"LocationTypeOfLocation": {
"Value": "Position",
"StringValue": "Position"
},
"LocationUserType": {
"Value": "RecordsWorker",
"StringValue": "Records Co-ordinator"
},
"TrimType": "Location",
"Uri": 64092
}
],
"PropertiesAndFields": {},
"TotalResults": 1,
"MinimumCount": 0,
"Count": 0,
"HasMoreItems": false,
"TrimType": "Location",
"ResponseStatus": {}
}
Is the error message just misleading? The structure is identical aside from the second (working) payload not having some of the fields present in the class. I'd expect this one to error if anything.
For what its worth I've also included the OrgSearchResult class below:
final class OrgSearchResult implements Serializable {
#JsonProperty("TrimType") private String trimType;
#JsonProperty("Uri") private String uri;
#JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>();
//getters and setters
A lot of troubleshooting. I've even tried to use ignore properties can't seem to get them to work.
Full error:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "Results" (Class
sailpoint.doet.contentmanager.ContentManagerResponse), not marked as
ignorable at [Source: java.io.StringReader#5c6648b0; line: 1, column:
13] (through reference chain:
sailpoint.doet.contentmanager.ContentManagerResponse["Results"])
You can improve readability of POJO class by using PropertyNamingStrategy.UPPER_CAMEL_CASE strategy. Also, you can use JsonAnySetter annotation to read all extra properties. Below example shows how model could look like:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
System.out.println(mapper.readValue(jsonFile, ContentManagerResponse.class));
}
}
class ContentManagerResponse {
private List<OrgSearchResult> results;
private Map<String, Object> propertiesAndFields;
private Integer totalResults;
private String countStringEx;
private Integer minimumCount;
private Integer count;
private Boolean hasMoreItems;
private String searchTitle;
private String hitHighlightString;
private String trimType;
private Map<String, Object> responseStatus;
// getters, setters, toString
}
class OrgSearchResult {
private String trimType;
private String uri;
private Map<String, Object> additionalProperties = new HashMap<>();
#JsonAnySetter
public void additionalProperties(String name, Object value) {
additionalProperties.put(name, value);
}
// getters, setters, toString
}
For first JSON payload above code prints:
ContentManagerResponse{results=[OrgSearchResult{trimType='Location', uri='1684', additionalProperties={}}], propertiesAndFields={}, totalResults=1, countStringEx='1 Location', minimumCount=1, count=0, hasMoreItems=false, searchTitle='Locations - type:Organization and id:24221', hitHighlightString='', trimType='Location', responseStatus='{}'}
For second JSON payload above code prints:
ContentManagerResponse{results=[OrgSearchResult{trimType='Location', uri='64092', additionalProperties={LocationSortName={Value=GW_POS_3}, LocationUserType={Value=RecordsWorker, StringValue=Records Co-ordinator}, LocationIsWithin={Value=true}, LocationTypeOfLocation={Value=Position, StringValue=Position}}}], propertiesAndFields={}, totalResults=1, countStringEx='null', minimumCount=0, count=0, hasMoreItems=false, searchTitle='null', hitHighlightString='null', trimType='Location', responseStatus='{}'}
You do not need to implement Serializable interface.
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.
I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.
I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.
I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)
{
"return": {
"entities": [
{
"id": 2385,
"details": [
{
"name": "Other Known Name",
"value": "John Wick",
"match": false
}
],
"proofs": [],
"link": "http://domain.gg/users?id=2385"
},
{
"id": 2384,
"details": [
{
"name": "Discord ID",
"value": "159985870458322944",
"match": false
},
{
"name": "SteamID64",
"value": "76561197991558078",
"match": true
},
{
"name": "SteamVanity",
"value": "test",
"match": false
},
{
"name": "PS4",
"value": "John_S",
"match": false
},
{
"name": "XBox",
"value": "John S",
"match": false
},
{
"name": "Email",
"value": "john_smith#gmail.com",
"match": true
},
{
"name": "Comment",
"value": "Test user",
"match": false
},
{
"name": "Other Known Name",
"value": "Jonathan",
"match": false
},
{
"name": "Reddit",
"value": "/u/johns",
"match": true
}
],
"proofs": [],
"link": "http://domain.gg/users?id=2384"
},
{
"id": 1680,
"details": [
{
"name": "Other Known Name",
"value": "Johny",
"match": false
},
{
"name": "SteamID64",
"value": "76561198213003675",
"match": true
}
],
"proofs": [],
"link": "http://domain.gg/users?id=1680"
},
{
"id": 1689,
"details": [
{
"name": "Other Known Name",
"value": "JohnnyPeto",
"match": false
},
{
"name": "SteamID64",
"value": "76561198094228192",
"match": true
}
],
"proofs": [],
"link": "http://domain.gg/users?id=1689"
}
],
"notice": "Showing 4 out of 4 matches."
}
}
There are many json serialization/deserialization frameworks available. I would recommend having a look at Jackson.
Basically, you have to create Model corresponding to json schema and deserialize json into object. Based on the example in the question, model will look like this:
#JsonIgnoreProperties(ignoreUnknown = true)
class Response {
#JsonProperty("return")
private ResponseObject responseObject;
public ResponseObject getResponseObject() {
return responseObject;
}
public void setResponseObject(ResponseObject responseObject) {
this.responseObject = responseObject;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
class ResponseObject {
private List<Entity> entities;
public List<Entity> getEntities() {
return entities;
}
public void setEntities(List<Entity> entities) {
this.entities = entities;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
class Entity {
private String id;
private List<Details> details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
class Details {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Once the model is defined, you can use ObjectMapper class to perform serialization/deserialization, e.g.:
ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue("{\"return\": {\"entities\": [{\"id\": 2385,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"John Wick\",\"match\": false}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2385\"},{\"id\": 2384,\"details\": [{\"name\": \"Discord ID\",\"value\": \"159985870458322944\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561197991558078\",\"match\": true},{\"name\": \"SteamVanity\",\"value\": \"test\",\"match\": false},{\"name\": \"PS4\",\"value\": \"John_S\",\"match\": false},{\"name\": \"XBox\",\"value\": \"John S\",\"match\": false},{\"name\": \"Email\",\"value\": \"john_smith#gmail.com\",\"match\": true},{\"name\": \"Comment\",\"value\": \"Test user\",\"match\": false},{\"name\": \"Other Known Name\",\"value\": \"Jonathan\",\"match\": false},{\"name\": \"Reddit\",\"value\": \"/u/johns\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=2384\"},{\"id\": 1680,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"Johny\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198213003675\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1680\"},{\"id\": 1689,\"details\": [{\"name\": \"Other Known Name\",\"value\": \"JohnnyPeto\",\"match\": false},{\"name\": \"SteamID64\",\"value\": \"76561198094228192\",\"match\": true}],\"proofs\": [],\"link\": \"http://domain.gg/users?id=1689\"}],\"notice\": \"Showing 4 out of 4 matches.\"}}", Response.class);
System.out.println(response.getResponseObject().getEntities().get(0).getId());
Here's the Javadoc.
If I were you, I'd use Jackson, not GSON. It's specialized on JavaBeans-style mapping. Write classes like this:
public class Detail{
private String name;
private String value;
private boolean match;
// + getters / setters
}
public class Entity{
private int id;
private List<Detail> details;
private String link;
private List<String> proofs;
// you don't have any example data for this, so I'm assuming strings
// + getters / setters
}
public class Result{
private List<Entity> entities;
private String notice;
// + getters / setters
}
and do the conversion with something like
Result result = new ObjectMapper().readValue(json, Result.class);
As my fellow stackoverflow users have previously posted, for this kind of initilization Jackson API would be better. I have however posted the solution for your question with Gson.
I noticed that you like your details to be stored as a HashMap with id as key. However, it seems like this id is actually related to the entities and not to the details.
Disclaimer, I got lazy and used an online POJO generator because I did not want to create objects for all of the Json elements ;) It still showcases how it should be done:
class Main{
public static void main(String[] args) throws FileNotFoundException {
//this is just to load the json file
String input = new Scanner(new File("test.txt")).useDelimiter("\\Z").next();
System.out.println(input);
Gson gson = new Gson();
Example arr = gson.fromJson(input, Example.class);
System.out.println(arr);
}
public class Detail {
#SerializedName("name")
#Expose
public String name;
#SerializedName("value")
#Expose
public String value;
#SerializedName("match")
#Expose
public Boolean match;
#Override
public String toString() {
return "Detail [name=" + name + ", value=" + value + ", match=" + match + "]";
}
}
public class Entity {
#SerializedName("id")
#Expose
public Integer id;
#SerializedName("details")
#Expose
public List<Detail> details = null;
#SerializedName("proofs")
#Expose
public List<Object> proofs = null;
#SerializedName("link")
#Expose
public String link;
#Override
public String toString() {
return "Entity [id=" + id + ", details=" + details + ", proofs=" + proofs + ", link=" + link + "]";
}
}
public class Example {
#SerializedName("return")
#Expose
public Return _return;
#Override
public String toString() {
return "Example [_return=" + _return + "]";
}
}
public class Return {
#SerializedName("entities")
#Expose
public List<Entity> entities = null;
#SerializedName("notice")
#Expose
public String notice;
#Override
public String toString() {
return "Return [entities=" + entities + ", notice=" + notice + "]";
}
}
}
Output
Example [_return=Return [entities=[Entity [id=2385, details=[Detail [name=Other Known Name, value=John Wick, match=false]], proofs=[], link=http://domain.gg/users?id=2385], Entity [id=2384, details=[Detail [name=Discord ID, value=159985870458322944, match=false], Detail [name=SteamID64, value=76561197991558078, match=true], Detail [name=SteamVanity, value=test, match=false], Detail [name=PS4, value=John_S, match=false], Detail [name=XBox, value=John S, match=false], Detail [name=Email, value=john_smith#gmail.com, match=true], Detail [name=Comment, value=Test user, match=false], Detail [name=Other Known Name, value=Jonathan, match=false], Detail [name=Reddit, value=/u/johns, match=true]], proofs=[], link=http://domain.gg/users?id=2384], Entity [id=1680, details=[Detail [name=Other Known Name, value=Johny, match=false], Detail [name=SteamID64, value=76561198213003675, match=true]], proofs=[], link=http://domain.gg/users?id=1680], Entity [id=1689, details=[Detail [name=Other Known Name, value=JohnnyPeto, match=false], Detail [name=SteamID64, value=76561198094228192, match=true]], proofs=[], link=http://domain.gg/users?id=1689]], notice=Showing 4 out of 4 matches.]]
Despite there are answers suggesting you to use Jackson, you can still accomplish easily with Gson with its default configuration just creating proper relations between mappings:
// A generic response, parameterized with <T>, can hold any type except of primitives
final class Response<T> {
#SerializedName("return")
final T ret = null;
}
final class EntitiesAndNotice {
final List<Entity> entities = null;
final String notice = null;
}
final class Entity {
// Unlike Object and any its subclasses, `int` being a primitive cannot be nulled
// Simple 0 won't work either, because the compiler will inline it
// So it's a sort of cheating javac to return a value that holds 0 already
final int id = Integer.valueOf(0);
final List<Detail> details = null;
// Your JSON document does not provide enough info on the elements type
// So it depends on how Gson parses JSON tokens
final List<Object> proofs = null;
final URL link = null;
}
final class Detail {
final String name = null;
final String value = null;
// The same for primitive booleans, or Boolean.FALSE
final boolean match = Boolean.valueOf(false);
}
Example use:
private static final String JSON = "{\"return\":{\"entities\":[{\"id\":2385,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"John Wick\",\"match\":false}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2385\"},{\"id\":2384,\"details\":[{\"name\":\"Discord ID\",\"value\":\"159985870458322944\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561197991558078\",\"match\":true},{\"name\":\"SteamVanity\",\"value\":\"test\",\"match\":false},{\"name\":\"PS4\",\"value\":\"John_S\",\"match\":false},{\"name\":\"XBox\",\"value\":\"John S\",\"match\":false},{\"name\":\"Email\",\"value\":\"john_smith#gmail.com\",\"match\":true},{\"name\":\"Comment\",\"value\":\"Test user\",\"match\":false},{\"name\":\"Other Known Name\",\"value\":\"Jonathan\",\"match\":false},{\"name\":\"Reddit\",\"value\":\"/u/johns\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2384\"},{\"id\":1680,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"Johny\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198213003675\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1680\"},{\"id\":1689,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"JohnnyPeto\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198094228192\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1689\"}],\"notice\":\"Showing 4 out of 4 matches.\"}}";
private static final Gson gson = new Gson();
private static final TypeToken<Response<EntitiesAndNotice>> responseTypeToken = new TypeToken<Response<EntitiesAndNotice>>() {
};
public static void main(final String... args) {
final Response<EntitiesAndNotice> response = gson.fromJson(JSON, responseTypeToken.getType());
final String value = response.ret.entities.get(1).details.get(3).value;
System.out.println(value);
}
Output:
John_S
I am trying to map a json document from the jenkins API to my own java objects. The json document looks as follows:
{
"assignedLabels": [
{}
],
"mode": "EXCLUSIVE",
"nodeDescription": "Jenkins Master-Knoten",
"nodeName": "",
"numExecutors": 2,
"description": null,
"jobs": [
{
"name": "Job 1",
"url": "https://build.example.com/jenkins/job/Job1/",
"color": "disabled"
},
{
"name": "Job 2",
"url": "https://build.example.com/jenkins/job/Job2/",
"color": "blue"
}
],
"overallLoad": {},
"primaryView": {
"name": "Alle",
"url": "https://build.example.com/jenkins/"
},
"quietingDown": false,
"slaveAgentPort": 0,
"unlabeledLoad": {},
"useCrumbs": false,
"useSecurity": true,
"views": [
{
"name": "Selection",
"url": "https://build.example.com/jenkins/view/-All%Selection/"
},
{
"name": "All",
"url": "https://build.example.com/jenkins/"
}
]
}
My java model looks like this:
public class JenkinsServer {
private List<String> assignedLabels;
private String url;
private String mode;
private String nodeName;
private String nodeDescription;
private String description;
private boolean useSecurity;
private boolean quietingDown;
private JenkinsServerView primaryView;
private List<JenkinsServerView> views;
private List<JenkinsJob> jobs;
// getters & setters
}
What I am doing now is I call
Gson gson = new Gson();
JenkinsServer server = gson.fromJson( reader, JenkinsServer.class );
But I receive this exception
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 6 column 5
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
I've been searching the internet for a solution but could not figure out what I'm doing wrong. Maybe you guys know :-)
As #Gimby mentioned in the comment, the problem is in your json data.
Solution1:
As assignedLabels is an array of strings with empty values, one option is to change the json data without curly braces as follows:
"assignedLabels": []
Solution2:
add transient keyword to the variable in java class
private transient List<String> assignedLabels;
Solution3:
the last and clumsy way to achieve is to add #Expose annotation to the all the variables that you want to parse in your java class
public class JenkinsServer {
private List<String> assignedLabels;
#Expose
private String url;
#Expose
private String mode;
#Expose
private String nodeName;
#Expose
private String nodeDescription;
#Expose
private String description;
#Expose
private boolean useSecurity;
#Expose
private boolean quietingDown;
#Expose
private JenkinsServerView primaryView;
#Expose
private List<JenkinsServerView> views;
#Expose
private List<JenkinsJob> jobs;
// getters & setters methods
}
and then add the parsing logic to parse your json string to corresponding java object as follows:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
JenkinsServer server = gson.fromJson(reader, JenkinsServer.class);
This is my JSON:
{
"results": [
{
"user_id": "1",
"item_id": "18630",
"name": "Unnamed Item",
"price": "0",
"description": "",
"created_at": "2014-01-16 15:31:36",
"thumbnail": {
"image50": "http://www.example.com/adsa.jpg",
"image100": "hhttp://www.example.com/adsa.jpg"
},...
Am I doing the deserialization right?
public class ItemListModel {
private String user_id;
private String item_id;
private String name;
private String price;
private String category;
private ArrayList<ThumbnailResponse> thumbnail;
public ItemListModel(){}
// getters
}
public class ThumbnailResponse {
private String image50;
private String image100;
public ThumbnailResponse(){
}
//getters
}
I'm just confused, when do we use ArrayList, Array or List for array or object in the JSON file?
One more thing, do I need to make results as an array too if that's the case?
As you have given
"thumbnail": {
"image50": "http://www.example.com/adsa.jpg",
"image100": "hhttp://www.example.com/adsa.jpg"
}
is not a JsonArray. So you have no need to use ThumbnailResponse as an ArrayList into ItemListModel.
Your Model should be
public class ItemListModel {
private String user_id;
private String item_id;
private String name;
private String price;
private String category;
private ThumbnailResponse thumbnail; // Not array List
public ItemListModel(){}
// getters
}
And
One more thing, do I need to make results as an array too if that's
the case?
Your main data container should be contain ArrayList of ItemListModel. Like below
ArrayList<ItemListModel> results = new ArrayList<ItemListModel>();
[] in json -> array
{} in json -> object or map
in your case
// change
private ArrayList<ThumbnailResponse> thumbnail;
// to
private Map<String,String> thumbnail;
if you want it the way you declared your java object you need to provide a transformer (depends on the framework you are using)
List<ItemListModel > ItemListModel ;
try {
Type listType = new TypeToken<List<ItemListModel >>(){}.getType();
result= (List<ItemListModel >) gson.fromJson(result, listType);
} catch (Exception e) {
Log.e("Parsing exeption", e.getLocalizedMessage(), e);
}
this should work
I have a very long JSON to parse with Gson, but for brevity I have trimmed it to this example:
{
"volumes": [
{
"status": "available",
"managed": true,
"name": "va_85621143-1133-412f-83b4-57a01a552638_",
"support": {
"status": "supported"
},
"storage_pool": "pfm9253_pfm9254_new",
"id": "afb8e294-6188-4907-9f6f-963c7623cecb",
"size": 9
},
{
"status": "in-use",
"managed": false,
"name": "bt_newd20",
"support": {
"status": "not_supported",
"reasons": [
"This volume is not a candidate for management because it is already attached to a virtual machine. To manage this volume with PowerVC, select the virtual machine to which the volume is attached for management. The attached volume will be automatically included for management."
]
},
"storage_pool": "KVM",
"mapped_wwpns": [
"2101001B32BD4280",
"2100001B329D4280",
"2101001B32BD637E",
"2100001B329D637E"
],
"id": "c7838c79-17ca-3cbc-98e5-3567fde902d8",
"size": 0
},
{
"status": "available",
"managed": true,
"name": "vdisk138",
"support": {
"status": "supported"
},
"storage_pool": "Chassis2_IBMi",
"id": "b6d00783-9f8c-40b8-ad78-956b0299478c",
"size": 100
}
]
}
From SO and few other places, I have found that I need to define a top level container like one below but I do not know how to complete its definition
static class VolumeContainer {
//I don't know what do in here. This is the first problem
}
and then a class for each Volume
static class Volume {
private String status;
private boolean managed;
private String name;
//This is the second problem.The "support" variable should not be a string.
//It is in {}. Just for information, I won't use it.
//private String support;
private String storagePool;
private List<String> mapped_wwpns;
private String id;
private String size;
}
I am trying to parse it and this is what I coded so far:
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(response).getAsJsonObject();
Gson gson = new Gson();
The JSON string is stored in a variable named response
VolumeContainer vc = gson.fromJson(response,VolumeContainer.class);
My final requirement is a HashTable of id and associated name.
First problem: your VolumeContainer needs to be:
public class VolumeContainer {
public List<Volume> volumes;
}
it does not need to be static.
Second problem: your Volume class should be like this:
public class Volume {
private String status;
private Boolean managed;
private String name;
private Support support;
private String storage_pool;
private String id;
private int size;
private List<String> mapped_wwpns;
public String getId(){return id;}
public String getName(){return name;}
}
I defined a class named Support like this:
public class Support {
private String status;
private List<String> reasons;
}
Third problem: parsing, If response string contains your example data, simply parse like this:
Gson g = new Gson();
VolumeContainer vc = g.fromJson(response, VolumeContainer.class);
Fourth problem: get the map. Finally to get your HashMap, just do like this:
HashMap<String, String> hm = new HashMap<String,String>();
for(Volume v: vc.volumes){
hm.put(v.getId(), v.getName());
}