serialization object reference with Gson - java

I'm working on a map builder application.
It have bus, train, stations, and lines between stations.
All those data are stored in a class called 'Map'.
I need to store my Map instance into a JSON file. I choose to use Gson.
Here's my Map, Line and Station classes:
public class Map
{
private LinkedList<Station> stations;
private LinkedList<Line> lines;
// methods ...
}
public class Line
{
private String name;
private LinkedList<Station> stations;
// methods
}
public class Station
{
private int number;
private String name;
private double latitude;
private double longitude;
private String cityName;
// methods
}
My problem is than all my object are store as independent object (without any reference).
As you can see map contains stations and lines. And lines contains stations.
When I load the JSON, and change a station in the map class, the same station doesn't change because it's not linked by reference.

Take a look at this one.
http://code.google.com/p/json-io/
See if it preserves your 'graph of objects' semantics.
Also look at:
http://benjamin.smedbergs.us/blog/2008-08-21/json-serialization-of-interconnected-object-graphs/
http://www.jspon.org/#JSPON%20Core%20Spec
I am not really sure JSON in its original form supports what you want (and you want to
serialize and then properly deserialize a whole graph of objects, not just a tree of objects).
I guess JSON does not support that but I am not 100% sure (I haven't needed that myself).
In a tree each object has just 1 parent, so there you don't have issues.
In a graph you may have objects A and B both pointing to some object C.
So how do you serialize C now? Do you do it in A (i.e. while serializing A) or in B, or outside of both A and B, and then have A and B point to that single serialized C somehow? Or do you just serialize C twice (once in A and once in B)? Btw, isn't it the
same with XML? I guess both XML and JSON are not designed for this.

Related

How to use an object's class variables to identify an object in java?

I created a class and made 57 objects from it, each one has specific ID number.
Can I create a method which returns an object using an ID as the argument?
For example, assume the name of my class is Things and I made two object from it called apple and dog, they have IDs 1 and 2.
Things.java:
class Things {
private String name;
private int ID;
public Things(String name, int ID) {
this.name = name;
this.ID = ID;
}
}
Main.java:
class Main {
public static void main(String[] args) {
Things apple = new Things("apple", 1);
Things dog = new Things("dog", 2);
}
}
in this example I want to create a method in class "Things" which returns object apple if I use 1 as argument and object dog if I use 2 .
You cannot identify objects by a particular property unless you store it in a special repository
You can create a ThingRepository and can get specific Things by the id.
public class ThingRepository {
private Map<Integer, Things> thingsRepository = new HashMap<>();
public void addThing(int id, Things things) {
thingsRepository.put(id, things);
}
public Things getThingById(int id) {
return thingsRepository.get(id); //Can return null if not present
}
}
The addThing method need not explicitly take the id. If you add a getter to Things, then it can be simplified to
public void addThing(Things things) {
thingsRepository.put(things.getId(), things);
}
Couple of problems you need to address:
Each created Things object has to be added to this somehow (either the caller needs to add or there must be some other wrapper/factory that must do this).
Once a Things is not needed, it must be removed from the above map, else it can lead to memory leak.
Btw, shouldn't Things be named as just a Thing?
There are two aspects here:
you need some sort of data structure that remembers about created objects, and allows you to access them by id, for example a simple Map<Integer, Things>. Each time you create a new Things (should better be called Thing, shouldn't it?!), you go thatMap.put(newId, newThing).
if you want that data to "survive", you would have to somehow persist it (like writing data to a file, database, ...)
If you use Intellij for example press: alt + insert and choose getters/setter.
If not just write your own getters/setter ;).
Like here: https://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
But basically if you want to look for Thing with particular Id you need to store somewhere them for example in ArrayList, then iterate through it and if your find element with that Id just return it.
1) Create new ArrayList
2) Iterate through
3) If you find Thing with Id you want, return it.

Update java object's properties by another object of same type

can you give me example how to update values in one object by another object of same type? For example here is my class:
public class MyObj {
private int id;
private String name;
private String phone;
private String address;
// some getters and settters ...
}
And I have another class with that stuff:
private ArrayList<MyObj> objectsList; // list of some objects
public MyObj update ( MyObj newObj ) {
// here I need set new values of properties of newObj to object with same id property in objectsList;
}
Exist some way how to do that without manually setting up all properties?
You have to identify the object in the list by iterating on it or replacing by a Map<String, MyObj>
Exist some way how to do that without manually setting up all
properties?
Sure.
Reflection addresses it but reflection has a cost (it is slower) and it may fail at runtime or give a unexpected behavior.
You can do it manually or better use a library that does the task for you.
But in your case, to handle just 3 fields, it seems an overhead to use reflection.
Just use setters to set them :
MyObj existingObj = ...; // retrieved by a search
existingObj.setName(newObj.getName());
existingObj.setPhone(newObj.getPhone());
existingObj.setAddress(newObj.getAddress());
As alternative, if changing the reference of the object is not a concern, just replace the object actually in the list by which one provided in parameter :
int indexOfTheObject = ...; // retrieved by a search
objectsList.set(indexOfTheObject, newObj);

Save a list of objects to ORMLite database

I am looking for a way to save a list of objects to the database with ORMLite and read upon this question: Best way to store several ArrayLists in ORMLite for ApplicationSettings
And the accepted answer makes sense to me:
public class YourClass {
#GeneratedId
private int id;
#ForeignCollectionField
private Collection<MyString> bunchOfStrings = new ArrayList<MyString>();
}
public class MyString{
#DatabaseField(canBeNull = true, foreign = true)
private YourClass yourClass;
#DatabaseField
private String text;
}
And the only thing that I don't understand is this line private Collection<MyString> bunchOfStrings = new ArrayList<MyString>(). Why do we save the ForeignCollectionField as Collection<MyString> instead of as ArrayList<MyString>? When working with the bunchOfStrings object above, do we always need to cast it to ArrayList<MyString>?
Why do we save the ForeignCollectionField as Collection
instead of as ArrayList?
That was design consideration, excerpt from doc
The field type of orders must be either ForeignCollection<T> or Collection<T> – no other
collections are supported because they are much heavier with many methods to support
When working with the bunchOfStrings object above, do we always need
to cast it to ArrayList
You dont have to initialize that field, Ormlite will do that. Hence, only available methods are ones present in Collection or ForeignCollection

Have Jackson parse Json object as primitive String

Simple question/problem for anybody familiar with building APIs... I have many objects that I prefer to represent as a string rather than a Json object, for simplicity purposes.
For example, I have a date range which I could (and used to) place into an object (with start end end date members), but considering we can have multiple of these ranges, I could instead have this...
['20130210-20130315','20130520-20130524']
Which IMO looks a lot simpler and cleaner than
[
{
"start":"2013-02-10",
"end":"2013-03-15"
},
{
"start":"2013-05-20",
"end":"2013-05-24"
}
]
And this holds for various other objects which are in the main Json object for the service.
My dilemma of just treating them as Strings is that then I lose the ability to mark them with interfaces, which are used all throughout the code. (For instance, this Json in particular might be marked with a "Filter" interface which many methods take in.)
That said, is there any way to satisfy both of these conditions, i.e. having a custom Json object (implementing my own interfaces, etc.) AND have Jackson parse it like a String primitive? I'm hoping this can be accomplished without much work involving custom serialization & deserialization, since I have lots of objects.
Hate duplicating posts, so in an attempt to add some value here -- this does exactly what I want with arrays --
public class MyAwesomeJson extends JacksonObject implements S {
private final String value;
public MyAwesomeJson(String value) {
this.value = value;
}
#JsonValue
public String getValue() {
return value;
}
}
Then to get the array form --
public class MyAwesomeJsonArray extends JacksonObject implements A {
private final Set<MyAwesomeJson> values = Sets.newLinkedHashSet();
public MyAwesomeJsonArray(MyAwesomeJson... values) {
this.values.addAll(Arrays.asList(values));
}
#JsonValue
public Set<MyAwesomeJson> getValues() {
return values;
}
}
System.out.println(new MyAwesomeJsonArray(new MyAwesomeJson("Yellow"),
new MyAwesomeJson("Goodbye")));
["Yellow","Goodbye"]

Assigning array of values to the corresponding objects dynamically

I have a question. I have 3 classes
public class cls1{
private String A;
private String B;
}
public class cls2{
private String C;
private String D;
}
public class cls3 extends cls1{
private String E;
private String F;
private cls2 cls2;
}
I have these 3 classes. cls1, cls2 are the normal classes but cls3 is extending cls1 and it has a component cls2.
I will query and get the results of cls3 from database but the output is in the form of "List". Object[] has all the cls3 parameters values. It includes cls1,cls2 parameters as well.
So here my question is how can I assign the values dynamically to all the classes. I will assign these values and I will use these values in some other place like "cls1.getA(), cls1.getB(), cls2.getC(), cls2.getD()" and so on.
So how can I assign array of values to these corresponding classes. I am thinking it's possible with BeanUtils. Is it possible with BeanUtils...?
Can anyone guide me on this please...
Use an ORM like hibernate. You need to map your domain model cls1,cl2,cls to your underlying persistence store using JPA. This is a much cleaner approach than rolling your own.

Categories