Gson is not formatting one variable from json string - java

I am trying to convert json format (arraylist response from rest webservice) to corresponding java arraylist.
Surpisingly, only 2 of 3 variables are getting formatted into object and 3 variable is setting into null.
Below is the json response in string format.
[{"points":"20","shares":"54","name":"Krishna"},{"points":"18","shares":"47","name":"Bhima"}]
I am trying to convert to arraylist with below code:
ArrayList<GplusFriend> gp_list;
Gson gson = new Gson();
gp_list = gson.fromJson(result, new TypeToken<List<GplusFriend>>(){}.getType());
Iterator itr = gp_list.iterator();
GplusFriend gf =null;
while(itr.hasNext()){
gf= (GplusFriend) itr.next();
Log.d("Restcall", "Name :"+gf.getName());
Log.d("Restcall", "points :"+gf.getPoints());
Log.d("Restcall", "shares :"+gf.getShares());
}
But I am getting the log as :
Name :null
points :20
shares :54
Name :null
points :18
shares :47
This is the class definition of GPlusFriend:
public class GplusFriend {
String Name;
String points;
String shares;
public String getShares() {
return shares;
}
public void setShares(String shares) {
this.shares = shares;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
public GplusFriend(){
super();
}
public GplusFriend(String Name,String points,String shares){
super();
this.shares=shares;
this.Name = Name;
this.points = points;
}
#Override
public String toString(){
return this.Name + " "+this.points+" "+this.shares;
}
}
So what I am missing here..

should be
String name;
instead of
String Name;
your JSON key is in small letter "name"
when using GSON, Variable names are case-sensitive

Related

Java - How can I create an array of a different class and iterate through it calling its toString method?

I have a Person class with the fields "name" and "phoneNumber" that are set through the constructor. I am trying to create a separate testing class that will create an array of Person and iterate through them by calling to their toString() method.
I am not sure how to do this, any help is appreciated.
Here is my first class which is all I have so far;
public class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Hope this will help,
public class Test {
public static void main(String[] args) {
Person array[] = {new Person("Jason", "123456"), new Person("Karl", "78945"), new Person("Tom", "789456")};
for(int i = 0; i < array.length; i++){
array[i].toString();
//System.out.println(array[i].toString());
}
}
}
class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Save the file as Test.java
Firstly the toString method is for an INDIVIDUAL Person object, and cannot be applied to a whole set, you need to make the method static and have a whole static array defined in the class to be able to go through all instances of the Person class.
private static Person[] pArray = new Person[20];
//I picked 20 randomly, if you want any possible number use an arrayList<Person>
private static int count = 0;
In the constructor
pArray[count] = this;
count++;
Then your toString method:
String list = "[";
for(Person p : this.pArray)
list = list + p.getPerson() + " ,"
list = list + "]";
return list;

Gson transform a field into multiple fields

Say I have serialized the following object as json string:
class Person {
public final String name;
public Person(String name) { this.name = name; }
}
Person p = new Person("Bob Falaway");
JsonObject json = gson.toJsonTree(p, Person.class).getAsJsonObject();
Now I want to deserialize it, but I want to split split the name into two fields, firstName and lastName. How do I do this?
I want the end to result in a class similar to:
class RefinedPerson {
public final String firstName;
public final String lastName;
public String toString() { return String.format("%s %s", firstName, lastName); }
}
Is this at all possible with Gson?
Register your own JsonSerializer for the type (or TypeAdapter if you'd prefer)?
Something like:
#JsonAdapter(PersonSerializer.class)
class Person {
private final String name;
Person(final String name) {
// Some validation...
this.name = name;
}
String getName() {
return this.name;
}
}
Where your serialiser looks something like:
class PersonSerializer implements JsonSerializer<Person> {
#Override
public JsonObject serialise(final Person src,
final Type personType,
final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
final String[] names = src.getName().split(" ");
// Some validation...
json.addProperty("firstName", names[0]);
json.addProperty("lastName", names[1]);
return json;
}
}

Deserializing arrays with protostuff

I am trying to use protostuff to serialize deserialize json but when i serialize the object the size of the array is put in front
{"id":1,"price":1.2,"name":"alex","tags":{"a":3,"b":["tag1","tag2","tag2"]}}
if i trie to desirialize the same string it works like a charm but my data dosent have "a":3,"b": for the tags its just simple
{"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]}
when i trie to desirialize a string like the above i get an exception thrown
io.protostuff.JsonInputException: Expected token: { but was VALUE_STRING on tags of message java.lang.reflect.Array
java code used:
String[] x = {"tag1", "tag2", "tag2"};
Product t = new Product(1, 1.2, "alex", x);
Path path = Paths.get("...");
byte[] as = Files.readAllBytes(path);
io.protostuff.Schema<Product> schema = RuntimeSchema.getSchema(Product.class);
LinkedBuffer buffer = LinkedBuffer.allocate(512);
byte[] protostuff;
try {
protostuff = JsonIOUtil.toByteArray(t, schema, false , buffer);
} finally {
buffer.clear();
}
// deser
Product f = schema.newMessage();
JsonIOUtil.mergeFrom(as, f, schema,false);
product class:
public class Product {
private int id;
private double price;
private String name;
private String[] tags;
public Product(int id, double price, String name, String[] tags) {
this.id = id;
this.price = price;
this.name = name;
this.tags = tags;
}
public Product() {
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public String[] getTags() {
return tags;
}
public void setId(int id) {
this.id = id;
}
public void setPrice(double price) {
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#Override
public String toString() {
return name+" "+ price+" "+ id+" "+ Arrays.toString(tags);
}
}
Protostuff uses special schema for serializing arrays - it puts array size to a serialized form for performance reasons.
You should change field type of tags to List:
private List<String> tags;
Lists are serialized directly into a JSON array:
{"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]}

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

new to java constructor help needed

I have an past exam question that says:
"Create a class Element that records the name of the element as a String and has a public method, toString that returns the String name. Define a constructor for the class (that should receive a String to initialise the name)."
I gave it a go and don't where to go from here...
main class is:
public class builder {
public static void main(String[] args) {
element builderObject = new element(elementName);
}
}
and constructor is:
import java.util.*;
class element {
public int getInt(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number");
String elementName = scan.nextLine();
System.out.println("%s");
}
public String toString() {
return elementName;
}
}
Don't get frustrated. Please read java tutorials first and understand the concepts. your exam question is very clear on what you need to do. Atleast for this question, you need to know what is constructor, the purpose of having toString() in a class.
May be the below can help you.
public class Element {
private String elementName;
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
I can't think of a way to explain this without actually giving the answer, so....
public class Element { /// Create class Element
private final String name; // Record the 'name'
public Element(String name) { // constructor receives and sets the name
this.name = name;
}
public String toString() { // public method toString() returns the name
return name;
}
}
You are missing the constructor itself. The point of constructors is to initialize the object, usually by saving the given parameters to data members.
E.g.:
class Element {
/** A data member to save the Element's name */
private String elementName;
/** A constructor from an Element's name*/
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
class Element {
private String name = "";
/**
/* Constructor
/**/
public void Element(final String name){
this.name = name;
}
#Override
public String toString(){
return name;
}
}
You don't have a constructor in there. A constructor typically looks something like this:
public class MyClass {
private String name;
private int age;
//This here is the constructor:
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
//here's a toString method just for demonstration
#Override
public String toString() {
return "Hello, my name is " + name + " and I am " + age + " years old!";
}
}
You should be able to use that as a guideline for making your own constructor.
class Element
{
private String name = "UNSET";
public String getName() { return name; }
public Element(String name) {
this.name = name;
}
public String toString() {
return getName();
}
}
You are missing a constructor you might be looking for something like this
public class Element{
private String name;
public Element(String name){ //Constructor is a method, having same name as class
this.name = name;
}
public String toString(){
return name;
}
}
A note
I take you are starting with java, In java class names usually start with capital letter, thus element should be Element. Its important that one picks up good habits early..

Categories

Resources