What I'm trying to do is to parse an object into a String, and then , parse it into an XML so any other language can translate it.
Figure out this object:
public class DatosPac
{
private String nombre;
private String apellidos;
private String dni;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
}
What I want to do is, parse it into a common XML between Android and .Net so both languages can translate the same object. The way to communicate both languages will be using Web Services, so the Web Service will receive a String, transalte it into the object and then use the information. Bidirectionally. I mean, Android will be able to receive an object parsed from .Net, and .Net will be able to receive the same object from Android. To be able to do this, I think I need to convert them into the same XML, but I don't know how to do it in Android.
Thanks in advance.
There are several XML serializing and de-serializing libraries available for Android. And I am sure the same's the case with .NET.
You set up your objects as POJOs and with a few annotations, you can serialize/deserialize in a few lines of code. In the Android world, I personally prefer Simple, but there are various other libraries available.
A more compact, (and more efficient, in terms of parsing) data representation format is JSON. There are multiple libraries available for parsing and constructing JSON too. My preferred one for Android is Gson.
EDIT: I believe I was a bit too quick! I didn't notice the android tag and assumed a .net context. Still, one bit stands: You probably want to serialize, not to "parse" the object, into XML.
Related
I've been trying to add Realm in my Android app. Their docs are pretty well explained & easy to follow. But it fails to explain this one particular area. I'm unable to figure out the practical use for the #Ignore annotation. I know that fields under this annotation are not persisted.
Can someone please share a few use cases. Also I wanted to know the scope of such fields. I mean, if I set an #Ignore field to some value, would that value be available to the other classes in my app for that particular launch session. If yes, then how do we access it? If no (which I guess is the case), then why do we need such a field anyway?
I've searched here and on web but couldn't find the relevant information. If out of my ignorance, I've missed upon some resource, please guide me to it.
Thanks.
Accordingly to the official documentation (see https://realm.io/docs/java/latest/) #Ignore is useful in two cases:
When you use GSON integration and your JSON contains more data than you want to store, but you still would like to parse it, and use right after.
You can't create custom getters and setter in classes extending RealmObject, since they are going to be overridden. But in case you want to have some custom logic anyway, ignored fields can be used as a hack to do that, because Realm doesn't override their getter & setters. Example:
package io.realm.entities;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
public class StringOnly extends RealmObject {
private String name;
#Ignore
private String kingName;
// custom setter
public void setKingName(String kingName) { setName("King " + kingName); }
// custom getter
public String getKingName() { return getName(); }
// setter and getter for 'name'
}
Ignored fields are accessible only from the object they were set in (same as with regular objects in Java).
UPDATE: As the #The-null-Pointer- pointed out in the comments the second point is out of date. Realm now allows having custom getters and setters in Realm models.
Here's a couple of real-world use cases:
1 - Get user's fullname:
public class User extends RealmObject {
private String first;
private String last;
#Ignore
private String fullName;
public String getFullName() {
return getFirst() + " " + getLast();
}
Get JSON representation of object:
public class User extends RealmObject {
private String first;
private String last;
#Ignore
private JSONObject Json;
public JSONObject getJson() {
try {
JSONObject dict = new JSONObject();
dict.put("first", getFirst());
dict.put("last", getLast());
return dict;
} catch (JSONException e) {
// log the exception
}
return null;
}
I've found it useful to define field names for when I am querying. For example
User.java
public class User extends RealmObject {
#Index
public String name;
#Ignore
public static final String NAME = "name";
}
And then later on I can do something like:
realm.where(User.class).equalTo(User.NAME, "John").findFirst();
This way if the schema changes from say name to id I don't have to hunt down every occurrence of "name".
Please see the the official documentation about #Ignore annotation:
The annotation #Ignore implies that a field should not be persisted to disk. Ignored fields are useful if your input contains more fields than your model, and you don’t wish to have many special cases for handling these unused data fields.
I have an android application that reads an XML file and presents some information to the user. The data structure is a simple ArrayList. The user goes through the list and they may make changes or they may not make changes just depending. When they are done they save.
Eventually we want that data on the RDBMS but they may not have a data connection at that exact moment so I need to persist it. Even if they do have a data connection I would probably feel comfortable knowing I have the data structure serialized to the sd card.
So step one is do I persist it in a binary state (it is a very small data object) or serialize it out to XML which is what I was thinking at first. That way it can be uploaded to a web service in it's xml form.
If I serialize it out to XML are there any libraries / example I can read up on. I use SAX to parse it but was thinking there must be something like a simple overload to dump it out????
pseudo code:
ArrayList<MyOb>;
MyObj.Serialize("doc.xml");
If I persist it in it's binary state what are the steps I need to consider when the user does have a data connection and it is time ti upload.
TIA
JB
You can use a great library JAXB(Java Architecture for XML Binding) for
JAVA Beans <---> XML Data
JAXB Basic Tutorial
Here is some sample code to give you some taste of it
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
XML formed using this code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
I'm going with persisting the data as xml on the sdcard. It's the best method from what I can discern.
In android, I'm using model classes with methods to handle the data manipulation. My data is brought in from webservices as json. I'm contemplating the possibility of using JSONObjects to store the values of class level attributes. But, I don't know of a way to use the JSONObj as the "holder" variable and create access methods. I don't want to predetermine these methods, as jsonRepository should hold the values, not always known at design time
For example, I'd like to have:
public class User {
private JSONObject jsonAttributes;
public User(String json) {
this.jsonAttributes= new JSONObject(json);
}
[IMPLICIT attribute access methods]
public string Prop1() returns jsonAttributes.getString("prop1");
public string Prop1(String newProp1) returns jsonAttributes.putString("prop1",newProp1);
public string Prop2() returns jsonRepository.getString("id");
public string Prop2(String newProp2) returns jsonAttributes.putString("prop2",newProp2);
....
from outside this class then, I would access the attributes simply...
User myUser = new User(someValidJson);
String myString = myUser.Prop1
Misguided? If not, how does one manage implicit property setting/getting?
As was mentioned in the comment above, why not create your user class, with all of the relevant memeber variables, and simply parse your JSON data in order to populate the ionformation in your user class.
There are a lot of ways you can do this, but I would consider using the builder pattern, as it is flexible, which could be useful if your JSON data changes in the future.
I have the following class definition:
public class Message {
private String sender, text;
public Message(String sender, String text) {
this.sender = sender;
this.text = text;
}
}
I would like to be able to send an instance of this Message class over a bluetooth socket. In order to do this, it will need to be converted into a byte[]. After it has been sent, I need to convert it back to a Message object (on the other side of the socket). How can I achieve this?
Two possible answers
Serializable vs Parcelable
Serializable relatively easy to implement but not efficient in term of memory and CPU
http://developer.android.com/reference/java/io/Serializable.html
Parcelable more complex to implement but more efficient in term of memory and CPU
http://developer.android.com/reference/android/os/Parcelable.html
Look into serialization.
http://developer.android.com/reference/java/io/Serializable.html
You could define a function, which returns a byte[] and just call it before you send it per bluetooth. The byte-array could be like { sendersize, textsize, sender, text }. Define also a function which reverts the process and call it on the other side.
I am having a problem with rest and android,
the problem is I have a transport object in example a class Human, which is extended by Male and Female, I want to use json as transport for the human object.
if I use standard serialized objects, i would usually do
if(human instanceof Male.class){}
else if(human instance of Female.class){}
else{ throw new RuntimeException("incorrect class")}
how do I implement this in android with rest?
I've seen that Gson and Jaskson which do not support polymorphism,
on the server side we're using Apache CXF for rest, with jax-rs annotations
Ideas/previous experiences??
I don't know of any automatic way to perform de-serialization, but one solution is to use a "duck typing" parser for your JSON.
Assume the following
class Human {
public Human(JSONObject jo) {
// Parse out common json elements
}
}
class Male {
private boolean hasMaleParts;
public Male(JSONObject jo) {
super(jo);
// Parse out male only parts
}
}
class Female {
private boolean hasFemaleParts;
public Female(JSONObject jo) {
super(jo);
// Parse out female only parts
}
}
With these three classes, somewhere in your network access code, have a method which types your returned JSON and returns the appropriate object.
public Human typeJson(JSONObject jo) {
if(jo.hasBoolean(hasMaleParts))
return new Male(jo);
else if(jo.hasBoolean(hasFemaleParts))
return new Female(jo);
else
throw new RuntimeException("Unable to determine data type");
}
In this example hasMaleParts and hasFemaleParts are arbitrary boolean flags, however, in many instances you could (more properly) type it using identifying attributes. So, if you were trying to distinguish between Motorcycle and Car, you might check number_of_wheels.