Gson : Iterating over fromJson result - java

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".)

Related

Java Vector: Each element contains three objects. How to operate based on the value of one of them?

For example, I have vector(object1, object2, price). How can I print elements where price > 100?
All the tutorials and documents (concerning operating in such way) I have seen only handle vectors where each element contains only one object.
So how can I get a handle on one specific object inside element? Or is this even possible?
A side question: what are those called? That is, if a single element is comprised of several items, what are those items called? Like in databases, a record is comprised of fields. Hard to google stuff you do not know the name of.
Main:
import java.util.Vector;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String type;
String location;
double value;
System.out.print("type->");
type=sc.nextLine();
System.out.print("location->");
location=sc.nextLine();
Property prop=new Property(type,location);
System.out.print("value->");
value=sc.nextDouble();
InsuranceInfo insu=new InsuranceInfo(prop,value);
container.addInsuranceInfo(insu);
}
InsInfoContainer class:
public class InsInfoContainer {
private Vector<InsuranceInfo> container;
public InsInfoContainer() {
container = new Vector<>(3, 1);
}
public void addInsuranceInfo(InsuranceInfo insu) {
container.addElement(insu);
}
public void print() {
Iterator<InsuranceInfo> iter = container.iterator();
while (iter.hasNext()) {System.out.println(iter.next());}
}
InsuranceInfo class:
public class InsuranceInfo {
public InsuranceInfo(Property prop, double value) {
this.prop = prop;
this.value = value;
}
private Property prop;
private double value;
public Property getProp() {return prop;}
public void setProp(Property prop) {this.prop = prop;}
public double getValue() {return value;}
public void setValue(double value) {this.value= value;}
}
Property class:
public class Property {
private String type;
private String location;
public Property(final String type, final String location) {
this.type = type;
this.location = location;
}
public String getType() {return this.type;}
public void setType(final String type) {this.type = type;}
public String getLocation() {return this.location;}
public void setLocation(final String sijainti) {this.location = location;}
}
You have a container to store your InsuranceInfo:
private Vector<InsuranceInfo> container;
Your container is called Collection
Your InsuranceInfo instances inside your container are called element
Your "items" inside InsuranceInfo (Property, value) are called property or field of element
To iterate over your container collection, the usual ways are using for loop or foreach loop:
public void print() {
for (InsuranceInfo element: container) {
if (element.getValue() > 100) { // Here is your condition to filter elements
// Process your elements here
}
}
}
You can also use Iterator, Stream to do that.

How can i convert convert json to object with different field names GSON

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;
}

How to set entire enum list in a variable and then save it in MongoDB

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

GSON Parse string returns null?

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
}

Casting objects via reflection in Java

I am writing a deserializer method, which looks like so:
public <T> T deserialize(Object[] result, String[] fields, Class<T> type);
So basically I will be passed in a result array of data which is all objects, and a class type T which I need to convert the data in the array to the types in the given class, and create a new class of type T and return it. The String[] fields is the field names corresponding to the data in Object[] result. The field names will correspond to the Class T.
The casting will need to use reflection of the given class to find out the type of each field.
eg.
result = ["Mike", "London", 28];
fields = ["name", "location", "age" ];
Class T =
public class GivenClass{
private String name;
private String location;
private Integer age;
public GivenClass(String name, String location, Integer age){
this.name = name;
this.location = location;
this.age = age;
}
}
Class implementation
static class GivenClass {
private String name;
private String location;
private Integer age;
public GivenClass(String name, String location, Integer age) {
this.name = name;
this.location = location;
this.age = age;
}
public GivenClass(Map<String, Object> data) throws Exception {
for (Field f : GivenClass.class.getDeclaredFields())
f.set(this, data.get(f.getName()));
}
public Map<String, Object> serialize() throws Exception {
Map<String, Object> fields = new HashMap<String, Object>();
for (Field f : GivenClass.class.getDeclaredFields())
fields.put(f.getName(), f.get(this));
return fields;
}
#Override
public String toString() {
return "age=" + age + ", location=" + location + ", name=" + name;
}
}
Example:
public static void main(String[] args) throws Exception {
GivenClass o1 = new GivenClass("Mike", "London", 28);
Map<String, Object> serialized = o1.serialize();
GivenClass o2 = new GivenClass(serialized);
System.out.println(o2.toString());
}
Output:
age=28, location=London, name=Mike
You need to do the conversion yourself. Reflections doesn't convert (it will only check the type of an object is already correct)
Reflections won't give you the names of method/constructor parameters. (You can get them from the debug byte code but that's a real pain)
The approach I take is to use the convention that the constructor parameters are in the same order as the fields. You will also want to assume the type of constructor parameters and field types match. ;)
I would also use primitives instead of wrappers whenever possible. Use int unless you want null to be a valid option. If this is the case you should think about how you want to represent this. For text I usually use empty strings or blank field for null or NaN depending on the context.
The problem with this, is that in Java it's unable to fetch the parameter names of a constructor.
For this particular example, you'll need a default constructor, with which you could create an empty object.
public GivenClass() {
super();
}
Then you could use reflection to get the fields of the class, and then set the appropriate value for them.
But I think it would be much easier to annotate your constructor, and then fetch the annotation informations in your deserialize method. In this case you won't need to fetch the fields and create an empty constructor.
Example:
You need to create a annotation like this:
#Target({ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
public #interface Property
{
String value();
}
And then you can use it in your constructor like this:
public GivenClass(#Property("name") String name, #Property("location") String location, #Property("age") Integer age) {
// ...
}
As Peter Lawrey says, casting does not convert a string into an integer.
If your bean follows the standard bean conventions (ie you have getters & setters), then you can use BeanUtils. BeanUtils does some standard conversions, and you can add more by adding a Convertor.
See the following example:
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
public static class Obj {
private int number;
private String string;
public void setNumber(int number) {
this.number = number;
}
public void setString(String string) {
this.string = string;
}
public String toString() {
return "number=" + number + " string=" + string;
}
}
public static void main(String args[]) throws Exception {
String[] values = new String[] { "1", "two" };
String[] properties = new String[] { "number", "string" };
Obj obj = new Obj();
for (int i = 0; i < properties.length; i++) {
BeanUtils.setProperty(obj, properties[i], values[i]);
}
System.out.println("obj=" + obj);
}
}
This produces as output:
obj=number=1 string=two
Note that the above example has only setters, but still works.

Categories