For some reason I am having issues with GSON parsing data from JSON_STRING. When I attempt to parse I am returned with null. Can you please help me with the code below and let me know where I went wrong? My objective is to ultimately parse JSON feed from url, but I figured to hard code the string for testing purpose.
import com.google.gson.Gson;
public class ReadJson {
public static void main(String... args) throws Exception {
String JSON_STRING =
"{\"data\":[{\"NAME\":\"Brandy\",\"LOCATION\":\"Redding, CA\"},
{\"NAME\":\"Jacob\",\"LOCATION\":\"Redding, CA\"},
{\"NAME\":\"Tatiana\",\"LOCATION\":\"Wonderland\"},
{\"NAME\":\"Tedo\",\"LOCATION\":\"Cottonwood\"}]}";
DataJSON data2 = new Gson().fromJson(JSON_STRING, DataJSON.class);
System.out.println(data2);
}
}
class DataJSON {
public String NAME;
public String LOCATION;
public String getName() { return NAME; }
public String getLocation() { return LOCATION;}
public void setName(String NAME) { this.NAME = NAME; }
public void setLoction(String LOCATION) { this.LOCATION = LOCATION; }
public String toString() {
return String.format("NAME:%s,LOCATION:%s", NAME, LOCATION);
}
}
Your JSON is an object with a single field (data) that contains an array of objects. You have a class that represents the objects inside the array (DataJSON)
Your POJO that Gson will deserialize to needs to be:
class MyData {
List<DataJSON> data;
}
If you then do:
MyData md = gson.fromJson(JSON_STRING, MyData.class);
It will deserialize properly.
You have a list in your json and so you need to wrap DataJSON inside a list. Something like this.
class DataJSONWrapper {
public List<DataJSON> list = new ArrayList<DataJSON>();
//getters & setters
}
Related
how can i convert this json:
[{"id":"0","value":1010},{"id":"1","value":"1000"},{"id":"2","value":"1111"}]
to single object having object having fields.
value0;(corresponds to id of value 0) it should be 1010
value1;(corresponds to id of value 1) it should be 1000
value2;(corresponds to id of value 2)
using GSON how can i implement it.
Create a Java Class according to your json object field like:-
public class Example {
private String id;
private String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
And one more class to represent arrays of json value to JAVA objects:-
public class JSONExample {
List<Example> examples;
public List<Example> getExamples() {
return examples;
}
public void setExamples(List<Example> examples) {
this.examples = examples;
}
}
Then you can loop your JSON object/array to create "Example" java
Object and using the same create JSONExample object.
Thats It.
It is going to be something like below :
String yourJson = "[{"id":"0","value":1010},{"id":"1","value":"1000"},{"id":"2","value":"1111"}]";
Gson gson = new Gson();
YourObject[] yourObjectArr= gson.fromJson(yourJson, YourObject[].class);
class YourObject
{
String id;
String value;
}
I need to save Enum data in MongoDB, for this I am able to get the Enum data but not getting how to set it. I am using Enum in a POJO and need to save that POJO containing Enum in MongoDB, used Gson for this.
import javax.annotation.Generated;
#Generated("org.jsonschema2pojo")
public class Coverage1 {
public enum Coverage {
Hearing_Aid_Professional_Liability("HEAR"), Incidental_Motorized_Land_Conveyances_Liability_Only("LANDC"), PremisesOperations_334("PREM"), Rental_Reimbursement("RREIM"), Liquor_Law_Liability_332("LLL"), Wind("WIND"), Business_Personal_Property("BPP"), OpticianOptometrists_Professional_Liability("OOPRL"), Builders_Risk("BLDRK"), Incidental_Farming_Personal_Liability("IFPL");
private String val;
Coverage(String val){
this.val = val;
}
public String getVal ()
{
return this.val;
}
public void setVal (String val)
{
this.val = val;
}
}
public Coverage value;
public Coverage getValue() {
return value;
}
public void setValue(Coverage value) {
this.value = value;
}
private String id;
private CoverageCd coverageCd;
private CoverageDesc coverageDesc;
private CoverageTypeCd coverageTypeCd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public CoverageCd getCoverageCd() {
return coverageCd;
}
public void setCoverageCd(CoverageCd coverageCd) {
this.coverageCd = coverageCd;
}
public CoverageDesc getCoverageDesc() {
return coverageDesc;
}
public void setCoverageDesc(CoverageDesc coverageDesc) {
this.coverageDesc = coverageDesc;
}*
public CoverageTypeCd getCoverageTypeCd() {
return coverageTypeCd;
}
public void setCoverageTypeCd(CoverageTypeCd coverageTypeCd) {
this.coverageTypeCd = coverageTypeCd;
}
}
In another class I am calling it from where i need to save it in Mongo DB.
Coverage1 cv= new Coverage1();
List<Coverage1.Coverage> ae= new ArrayList<Coverage1.Coverage>();
for(Coverage1.Coverage enumval:Coverage1.Coverage.values()){
//ae=enumval;
System.out.println(enumval);
cv.setValue(enumval);//I need to set the entire Enum data here, so that it could be saved in Mongo. But not getting how to save the entire data
}
cv.setId("1");
Gson gson = new Gson();
String json = gson.toJson(cv);
System.out.println(json);
// Parse to bson document and insert
Document doc = Document.parse(json);
db.getCollection("NameColl").insertOne(doc);
Please someone help me how to save the entire Enum data in Mongo document.
You could regenerate the correct schema with a list of your coverage values in your JSON, but this needs to be a list
public Coverage1.Coverage[] values;
Therefore, change the getters and setters as well.
Then, you can cv.setValues(Coverage1.Coverage.values());
Or maybe, you tried to do this
List<Coverage1.Coverage> ae= new ArrayList<Coverage1.Coverage>(Arrays.asList( Coverage1.Coverage.values());
Or,
for(Coverage1.Coverage enumval: Coverage1.Coverage.values() ){
ae.add(enumval);
}
Basically, cv.setValue(enumval); can't be done in a loop because you'll overwrite the one value
I'd also suggest better names for the enum. And the one at the end of Coverage1 could be removed
Got into a very basic issue. I have to convert json string to objects. I have a custom method as below which is expected to convert into corresponding class and throw an exception if it is not able to get the object out of it.
protected <T> T getObjectFromJson(Class<T> c, String json){
try{
Gson gson = new Gson();
T object = gson.fromJson(json, c);
return object;
} catch (Exception e){
throw new TMMIDClassConversionException(e.getCause(), e.getMessage());
}
}
The issue is this method is not throwing exception if I am trying to convert json of a different class.
My class
public class CompanyCategoryMap {
private Integer id;
private int mid;
private String catKey;
private String catValue;
private int priority;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getMid() {
return mid;
}
public void setMid(int mid) {
this.mid = mid;
}
public String getCatKey() {
return catKey;
}
public void setCatKey(String catKey) {
this.catKey = catKey;
}
public String getCatValue() {
return catValue;
}
public void setCatValue(String catValue) {
this.catValue = catValue;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
}
When I pass json string of Company rather than String of above class, it does not throw exception.
The string:
"{\"id\":6,\"name\":\"abc\",\"usersCount\":10,\"mid\":3,\"createdAt\":\"Sep 15, 2014 7:02:19 PM\",\"updatedAt\":\"Sep 15, 2014 7:02:19 PM\",\"active\":true,\"currency\":\"abc\",\"source\":\"unknown\",\"user_id\":1,\"tierId\":1}"
I think I am doing this conversion in a wrong way. What is the suggested way of doing it?
Take for example:
class Foo {
private String value;
}
class Bar {
private String value;
}
and
String json = "{\"value\" : \"whatever\"}";
new Gson().fromJson(json, Foo.class);
new Gson().fromJson(json, Bar.class);
Why should Gson reject any of these?
Gson is setup to perform a best effort to deserialize the given JSON into an instance of the given Class. It will map as many fields as it finds. If none are found, that's too bad.
Other libraries like Jackson do the opposite. By default, Jackson rejects any JSON which doesn't contain a mapping for every given class property. You can also configure it to ignore some properties.
Keep doing what you are doing. As the application writer, you should know when to use a Class instance with the appropriate JSON source.
I am returning an array of results with my json Objects, and I am trying to use my customObjectResponse class to pull out each of the fields within each of the objects... the problem it is expecting an object so how do I edit my class to allow it to take in an array of object to be able to then call the fields of each object... I am confused as to what needs to be added:
Here is a response example of what is being passed to be used:
[
{
itemId: 'dfsdfsdf343434',
name: 'tests',
picture: '6976-7jv8h5.jpg',
description: 'testy.',
dateUpdated: 1395101819,
}
]
Here is my response Object Class:
public class ObjResponse{
private String itemId;
private String name;
private String picture;
private String description;
private String location;
private int dateUpdated;
private String msg;
//gridview constructor
public ObjResponse(String picture) {
this.picture = picture;
}
//public constructor
public ObjResponse() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(int dateUpdated) {
this.dateUpdated = dateUpdated;
}
public String getMsg() {
return msg;
}
}
what I am trying, but is not working, even if I separate the classes into their own files:
Data passed in:
items: [{obj1: "A", obj2: ["c", "d"]}, {etc...}]
public class Response {
public class List<Custom> {
private List<Custom> items;
}
public class Custom {
private String obj1;
private List<Obj2> obj2;
}
public Class Obj2 {
private String letters;
}
}
I ended up just calling in the callback a list of the customObject and it did the job...
new Callback<List<ObjResponse>>() {
I originally had trouble getting an idea of how the OP solved his problem but, after days of debugging I have finally figured out how to solve this issue.
So you essentially have data in the format like so (JSON Array of JSON Objects):
[
{
...
}
]
Your class that models the data and contains the getter and setter methods are nothing more than your typical POJO.
public class Person implements Serializable {
#SerializedName("Exact format of your json field name goes here")
private String firstName;
// Getters and Setters....
}
In your interface that contains your RESTful annotations you want to convert your call from:
Before:
public interface APInterface {
#GET("SOME URL TO YOUR JSON ARRAY")
Call<Person>(...)
}
After:
public interface APInterface {
#GET("SOME URL TO YOUR JSON ARRAY")
Call<List<Person>>(...)
}
In your android activity you want to convert all calls in the form of Call<Person> to Call<List<Person>>
Finally when making the initial asynchronous request call, you will want to convert your callbacks like so.
call.enqueue(new Callback<List<Person>>() {
#Override
public void onResponse(Call<List<Person>> call, Response<List<Person>> response) {
if(response.isSuccessful()){
List<Person> person = response.body();
// Can iterate through list and grab Getters from POJO
for(Person p: person){...}
} else {
// Error response...
}
}
#Override
public void onFailure(Call<List<Person>> call, Throwable t) {...}
});
Hope this helps others whom are lost from the accepted answer above.
This can also work by just passing an array of response objects. So if this is your response object:
public class CustomUserResponse {
public String firstName;
public String lastName;
...
}
You can use related syntax, depending on how you use the callbacks. Such as:
new Callback<CustomUserResponse[]>(){
#Override
public void success(CustomUserResponse[] customUserResponses, Response rawResponse) {
}
#Override
public void failure(RetrofitError error) {
}
};
OR
public class GetUserCommand implements Callback<CustomUserResponse[]> { ...
Put simply, in every place where you normally replace T with a response class, replace it with an array, instead as in CustomUserResponse[].
NOTE: to avoid confusing errors, be sure to also use an array in the Retrofit interface definition:
#POST ( "/users" )
public void listUsers(#Body GetUsersRequest request, Callback<CustomUserResponse[]> callback);
You could try something like this
JSONObject jsonObject = new JSONObject(<your JSON string result>);
JSONArray jsonArray = jsonObject.getJSONArray();
//use GSON to parse
if (jsonArray != null) {
Gson gson = new Gson();
ObjResponse[] objResponse = gson.fromJson(jsonArray.toString(), ObjResponse[].class);
List<ObjResponse> objResponseList = Arrays.asList(objResponse);
}
This should definitely work.
Language: Java and Gson
Having parsed a JSON array, how do I:
1) Print all of its contents
2) Iterate over its contents?
For example, here's my code:
String JSInput = "//Json String";
Type listType = new TypeToken<TabClass[]>() {}.getType();
Input_String =GsonObject.fromJson(JSInput, listType);
System.out.println(Input_String.toString());
And the corresponding class description is :
class TabClass{
String Name;
String Parent;
public String getName() {
return Name;
}
public String getParent() {
return Parent;
}
public void setName(String Name) {
this.Name = Name;
}
public void setParent(String Parent) {
this.Parent = Parent;
}
}
The above code only returns a description of the object along with its memory location:
[Lcom.example.projectname.TabClass;#1fbfd6
How do I print the contents of the resultant object, or Iterate over it?
It's not necessary to create a TypeToken just for an array. Gson will deserialize to an array type just fine.
If you have an array, then you don't have to explicitly iterate through its contents just to print. You can use one of the Arrays.toString() methods.
Here's an example.
// output:
// [{value1=one, value2=1}, {value1=two, value2=2}, {value1=three, value2=3}]
import java.util.Arrays;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args)
{
Gson GsonObject = new Gson();
String JSInput = "[{\"value1\":\"one\",\"value2\":1},{\"value1\":\"two\",\"value2\":2},{\"value1\":\"three\",\"value2\":3}]";
TabClass[] Input_String = GsonObject.fromJson(JSInput, TabClass[].class);
System.out.println(Arrays.toString(Input_String));
}
}
class TabClass
{
private String value1;
private int value2;
#Override
public String toString()
{
return String.format(
"{value1=%s, value2=%d}",
value1, value2);
}
}
Otherwise, if you'd rather explicitly iterate through the components of the array, with Java you have a few choices for how to do so. A simple one is to use the for-each loop construct.
for (TabClass tab : Input_String)
{
System.out.println(tab);
}
(By the way, "Input_String" is not a good name for this array of TabClass. A more descriptive name might be "tabs".)