#Order annotation has no effect on the XML serialization order - android

I'm using Retrofit 2 with a SimpleXmlConverter and I am facing an issue when creating a Soap Request Object, that is basically an element with 4 element children each one of them being different datatypes.
Here is the XML output I want to produce. The element order must be respected:
<prf:container>
<prf:aaa>111111111</prf:aaa>
<prf:bbb>true</prf:bbb>
<prf:element>
<prf:ddd>50</prf:ddd>
<prf:eee>false</prf:eee>
</prf:element>
<prf:ccc>textcontent</prf:ccc>
</prf:container>
Now, here is my Android Class, Container.java, representing the Soap Request Object that will be serialized:
#Root (name = "prf:container")
#Order(elements={"prf:aaa", "prf:bbb", "prf:element", "prf:ccc"})
public class Container {
#Element (name = "prf:aaa")
private int aaa;
#Element(name = "prf:bbb")
private boolean bbb;
#Element (name = "prf:element", required = false)
private MyElement myElement;
#Element (name = "prf:ccc", required = false)
private String ccc;
}
According to the Simple XML framework documentation:
By default serialization of fields is done in declaration order.
However, in Android, this is not true, at least in some cases. No matter how I set the field declaration order in my Container class, the output has always the same element order. This is a known bug and as has been reported in other SO posts.
Nonetheless, there is a solution to this issue. The Order annotation.
Read more in the Javadoc.
My problem is that using the Order annotation in my case is not helping. Note that all my elements have a prefix on its name - prf:.
If I remove the prf prefix from all my element names, Order annotation will work properly, and force the XML Serialization to have the defined order. But the output elements won't have the prefix on its name.
But I really need my elements to have the prefix on its name, or else my request will have a 500 response. I also have to have the desired element order in my XML output.
Any solution to this?
Thank you

I know it has been a long item since you posted this question but, I would like to answer your question in case anyone faced the same issue. I solved the same issue by doing the following:
For the XML document to be prepared with the elements in the order you want and if the elements have a prefix, #Order annotation might not work in some cases. In your case, the prefix 'prf' mentioned in the #Order annotation for each element would not work to order them as you desired.
"By default serialization of fields is done in declaration order."
I don't believe this either, especially when you have prefixes for elements. So, I tried changing the Java variable names. I tried naming them in alphabetical order in the same way I needed them in the generated xml. So, in your case, you can change the variable names as follows:
#Root (name = "prf:container")
public class Container {
#Element (name = "prf:aaa")
private int element1;
#Element(name = "prf:bbb")
private boolean element2;
#Element (name = "prf:element", required = false)
private MyElement element3;
#Element (name = "prf:ccc", required = false)
private String element4;
}
This would form the xml document exactly as you wanted. You might wonder that if we change the variable names to be too generic, they are not representing what they actually are but, you can always have getters and setters. For example, in your case you can have:
public void setAaa(String aaa){
this.element1 = aaa;
}
public String getAaa(){
return element1;
}
In the same way you can always generate the classes with alphabetically ordered variables to make sure the generated xml has the elements in the desired format.

Maybe you using #Order with wrong syntax,Alphabetical order is not important. You can try:
#Root (name = "prf:container")
#Order(elements={"prf:container/prf:aaa", "prf:container/prf:bbb", "prf:container/prf:element", "prf:container/prf:ccc"})
public class Container {
#Element (name = "prf:aaa")
private int aaa;
#Element(name = "prf:bbb")
private boolean bbb;
#Element (name = "prf:element", required = false)
private MyElement myElement;
#Element (name = "prf:ccc", required = false)
private String ccc;
}

SimpleXML's auto ordering by alphabetical order is working. But on one condition: the type of those fields should be the same, usually for XML it is String. It took me long time to figure that out, I had different types, and ordering by name didn't work. Since I've changed all fields to String works like a charm.
#Root(name = "sch:CheckPaymentRequest", strict = true)
public class CheckPaymentData {
#Element(name = "sch:payId")
private String Aaa1;
#Element(name = "sch:fromCurrency")
private String Bbb2;
#Element(name = "sch:fromAmount")
private String Ccc3;
...}

Related

Firestore - How to update a field that contains period(.) in it's key from Android?

Updating a field contains period (.) is not working as expected.
In docs, nested fields can be updated by providing dot-seperated filed path strings or by providing FieldPath objects.
So if I have a field and it's key is "com.example.android" how I can update this field (from Android)?
In my scenario I've to set the document if it's not exists otherwise update the document. So first set is creating filed contains periods like above and then trying update same field it's creating new field with nested fields because it contains periods.
db.collection(id).document(uid).update(pkg, score)
What you want to do is possible:
FieldPath field = FieldPath.of("com.example.android");
db.collection(collection).document(id).update(field, value);
This is happening because the . (dot) symbol is used as a separator between objects that exist within Cloud Firestore documents. That's why you have this behaviour. To solve this, please avoid using the . symbol inside the key of the object. So in order to solve this, you need to change the way you are setting that key. So please change the following key:
com.example.android
with
com_example_android
And you'll be able to update your property without any issue. This can be done in a very simple way, by encoding the key when you are adding data to the database. So please use the following method to encode the key:
private String encodeKey(String key) {
return key.replace(".", "_");
}
And this method, to decode the key:
private String decodeKey(String key) {
return key.replace("_", ".");
}
Edit:
Acording to your comment, if you have a key that looks like this:
com.social.game_1
This case can be solved in a very simple way, by encoding/decoding the key twice. First econde the _ to #, second encode . to _. When decoding, first decode _ to . and second, decode # to _. Let's take a very simple example:
String s = "com.social.game_1";
String s1 = encodeKeyOne(s);
String s2 = encodeKeyTwo(s1);
System.out.println(s2);
String s3 = decodeKeyOne(s2);
String s4 = decodeKeyTwo(s3);
System.out.println(s4);
Here are the corresponding methods:
private static String encodeKeyOne(String key) {
return key.replace("_", "#");
}
private static String encodeKeyTwo(String key) {
return key.replace(".", "_");
}
private static String decodeKeyOne(String key) {
return key.replace("_", ".");
}
private static String decodeKeyTwo(String key) {
return key.replace("#", "_");
}
The output will be:
com_social_game#1
com.social.game_1 //The exact same String as the initial one
But note, this is only an example, you can encode/decode this key according to the use-case of your app. This a very common practice when it comes to encoding/decoding strings.
Best way to overcome this behavior is to use the set method with a merge: true parameter.
Example:
db.collection(id).document(uid).set(new HashMap<>() {{
put(pkg, score);
}}, SetOptions.merge())
for the js version
firestore schema:
cars: {
toyota.rav4: $25k
}
js code
const price = '$25k'
const model = 'toyota.rav4'
const field = new firebase.firestore.FieldPath('cars', model)
return await firebase
.firestore()
.collection('teams')
.doc(teamId)
.update(field, price)
Key should not contains periods (.), since it's conflicting with nested fields. An ideal solution is don't make keys are dynamic, those can not be determined. Then you have full control over how the keys should be.

How to make many-to-many relation query in GreenDAO with source property other than primary key?

Let's assume we have following entities:
Item:
class Item {
...
#Index(unique=true)
private String guid;
...
#ToMany
#JoinEntity(entity = JoinItemsWithTags.class, sourceProperty = "itemGuid", targetProperty = "tagName")
private List<Tag> tagsWithThisItem;
...
}
Tag:
class Tag {
#Id
private Long localId;
#Index(unique = true)
private String name;
...
}
and we need to join them. Here is my join entity class:
#Entity(nameInDb = "item_tag_relations")
class JoinItemsWithTags {
#Id
private Long id;
private String itemGuid;
private String tagName;
...
}
I want to use tag name as a join property instead of Long id, because it's easier to support consistency when syncing with server.
But currently tags getter in Item class always return an empty list. I've looked into log and found generated query which using internally in that getter:
SELECT * <<-- there were a long sequence of fields
FROM "tags" T JOIN item_tag_relations J1
ON T."_id"=J1."TAG_NAME" <<-- here is the problem, must be `T."NAME"=J1."TAG_NAME"`
WHERE J1."ITEM_GUID"=?
So the problem is that join is base on tag's _id field. Generated List<Tag> _queryItem_TagsWithThisItem(String itemGuid) method implicitly uses that id to make a join:
// this `join` nethod is overloaded and pass tag's id as source property
queryBuilder.join(JoinItemsWithTags.class, JoinItemsWithTagsDao.Properties.TagName)
.where(JoinItemsWithTagsDao.Properties.ItemGuid.eq(itemGuid));
Correct approach is this case might be following, I suppose:
// source property is passed explicitly
queryBuilder.join(/* Desired first parameter -->> */ TagDao.Properties.Name,
JoinItemsWithTags.class, JoinItemsWithTagsDao.Properties.TagName)
.where(JoinItemsWithTagsDao.Properties.ItemGuid.eq(itemGuid));
But this code is in generated dao, and I don't know how to do anything with it. Is there any way to workaround this?

serialVersionUID added to JSON

I am converting an object to JSON using com.google.code.gson:gson:2.2.4 library by using code:
String json = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED).create().toJson(object);
And in the JSON string "serialVersionUID" is added automatically with Long value even if it is not in a model class. I just want to remove serialVersionUID from JSON.
I found this answer. Basically, the serialVersionUID is added by InstantRun, disabling InstantRun solved the issue for me.
One way to get around this is to use GsonBuilder.excludeFieldsWithoutExposeAnnotation then use the #Expose annotation to explicitly mark what is or isn't (de)serialized.
public class SomeClass {
private int field1 = 2;
#Expose private int field2 = 6;
#Expose #SerializedName ("foo") private int field3 = 12;
}
gives you {"field2":6, "foo":12}. The field field1 is excluded because it isn't annotated with #Expose.
Personally, I always use the GsonBuilder.excludeFieldsWithoutExposeAnnotation because it filters out any generated fields (like the Instant Run comment above). If you didn't annotate it with #Expose, it won't be serialized/deserialized.
Another way is to declare the field as transient.

SimpleXML Java - Read value in the root element

I am using SimpleXML for Java to parse a XML response to java class mapping. However, I am not able to get this particular piece working with my android device.
My XML fragment looks like this,
<t:EmailAddresses>
<t:Entry Key="EmailAddress1">sip:xxx#abs.com</t:Entry>
<t:Entry Key="EmailAddress2">smtp:xxx#abs.com</t:Entry>
<t:Entry Key="EmailAddress3">SMTP:xxx#abs.com</t:Entry>
</t:EmailAddresses>
and my Class definition for EmailAddresses looks like this,
#Root
public class EmailAddresses
{
#ElementList
private List<Entry> Entry;
public List<Entry> getEntry() { return Entry; }
public void setEntry(List<Entry> entry) { Entry = entry; }
}
And my Entry class looks like this,
#Element
public class Entry
{
#Attribute
private String Key;
public String getKey() { return Key; }
public void setKey(String key) { Key = key; }
}
when I parse run the parser, I only get the Keys and that also, I get "Multiple Root Elements" error when trying to parse all 3 into a List of Entry class.
Can someone please point me in the right direction?? Thanks !!
Note: The XML Namespace "t" is defined properly.
Here are some things you should change:
Class EmailAddresses
#Root(name = "EmailAddresses") /* 1 */
#Namespace(prefix = "t", reference = "INSERT YOUR REFERENCE HERE!") /* 2 */
public class EmailAddresses
{
#ElementList(inline = true) /* 3 */
private List<Entry> Entry;
// ...
}
Explanation:
/* 1 */: Set the name of the element (case sensitive); simple does this per default, but so you can ensure it's really correct.
/* 2 */: Set the namespace and it's reference; required for the t in your XML.
/* 3 */: Inline the list; the <t:EmailAddresses> element is constructed out of the #Root() element, all entries follow as
inline-elements. Otherwise the list will create another element as child,
wrapping it's entries.
Class Entry
#Root(name = "Entry") /* 1 */
#Namespace(prefix = "t", reference = "INSERT YOUR REFERENCE HERE!") /* 2 */
public class Entry
{
#Text
private String text; /* 3 */
#Attribute
private String Key;
// ...
}
Explanation:
/* 1 */: Don't use #Element here, use #Root().
/* 2 */: As #2 above.
/* 3 */: Your Entry-tags in the XML contain text (= value of the element, like the "sip:..."), those require a mapping too. If the text is optional, you can use #Text(required = false) to indicate that.
TIP: Create an instance of your list, fill it with entries and serialize it, e.g. into a file. So you can see if the mapping is matching your expectations, and where you have to do some corrections.
Can you not use attributes to extract the data? Here's a snippet from an RSS feed reader app that parses XML similarly:
if (localName.equals("channel"))
{
/** Get attribute value */
String attr = attributes.getValue("category");
itemList.setTitle(attr);
}

Android SimpleFramework Namespace prefix

on Android I'm using SimpleFramework to parse incoming XML and create appropriate objects (which are saved to DB afterwards...)
A part of XML looks like this:
<CheckId xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:guid>00300001-0000-0000-0000-000000000000</a:guid>
</CheckId>
Where <a:guid> can repeat 1..N
My element annotations look like this:
#ElementList(required = false, name="CheckId")
#Namespace(reference="http://schemas.microsoft.com/2003/10/Serialization/Arrays")
#ForeignCollectionField(eager = true, orderColumnName = "Guid", columnName = TABLE_CHECK_ID_LIST_COLUMN)
public Collection<TableCheck> TableCheckIdList;
and in the TableCheck class is:
#Root(name = "CheckId")
#Order(elements = { "guid" })
public static class TableCheck implements XMLParseable {
#Element(required = false, name="guid")
#DatabaseField
public String Guid;
...
}
After parsing is done, the Collection contains as many items as tag <a:guid> appeared in the XML. However, the property Guid is always NULL.
I've tried to play with Namespace / Prefix attributes but the result is always the same - NULL value in Guid property.
Any ideas?
This has nothing to do with the #Namespace annotation. Here Guid is null because of one of the following reasons.
a) It is written like <a:guid/>
b) It is written line <a:guid></a:guid>
c) Something is setting it to be null after you have finished parsing it.
Try using constructor injection and set the value as final, then you know nothing else is setting it to null after the object is created.

Categories

Resources