How #JsonProperty working using jackson parser in android - android

In this below code, if I access getBl_no () its correctly returning value. I don't know how it's working I didn't set bl_no anywhere is that Json property will set to that set method? Please anyone explain.
#JsonProperty("BL_NO")
private String bl_no;
public String getBl_no() {
return bl_no;
}
public void setBl_no(String bl_no) {
this.bl_no = bl_no;
}

#JsonProperty annotation is where the magic happens! The JSON parser that you use reads the JSON property named BL_NO and assigns its value to the private instance variable bl_no. You don't even need a setBl_no() method for this to work.
#JsonProperty annotation lets you tell the JSON parser that while serializing or deserializing, the JSON property BL_NO should be tied to variable bl_no. That's how the variable gets initialized with a value even though you don't explicitly do it.

Related

GSON : Custom serialization for String

public class Data{
public String str; //String (that may contain line breaks) I need to serialize as it is.
}
Why I needed custom Serializer for string?
Without custom serializer it serializes this as object {"str":{"count": 292,"hashCode": 0} }
I need it to be {"str":"..............."}
How to do it with custom Serializer?
There are example of custom serializer for custom types, but could not find anything that helps to serialize String type.
Well, Gson supports strings out of box and you don't have to implement any string serializer and vice versa yourself. What I guess might happen to your case is merely importing a wrong string class, say import foo.bar.baz.String; or less obvious import foo.bar.baz.*, or you just have a String class implementation right in the package where your Data class is declared in. (This cannot explain what values were really assigned to str, though, -- it would never work in Java causing ClassCastException). A wrong class might be indicated with numeric count and hashCode without any char[]-declared fields, so I don't believe this is a java.lang.String in your case. Also, a more hypothetical thing here might be use of reflection that discarded the string type adapter out of your Gson instance, no matter how and how weird it sounds. In any case, you don't have to implement even a single line to serialize Java strings with Gson.
Regarding the accepted answer: it is suboptimal. If, for whatever reason, there is nothing wrong with your imports, your package does not declare a custom String class, and your Gson instances do not suffer from reflection surgery, but Gson still serializes such strings as nested objects (have no ideas why then), you'd only need a single special String type adapter without any need of creating type adapters for any class that uses that weird String as a field:
final Gson gson = new GsonBuilder()
.registerTypeAdapter(/*real.package.here.*/String.class, (JsonSerializer</*real.package.here.*/String>) (s, type, context) -> new JsonPrimitive(s.toString())) // whatever the real Java string is obtained
.create();
Try this
public class DataSerializer implements JsonSerializer<Data> {
#Override
public JsonElement serialize(Data data, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("src", data.src);
return object;
}
}
Add this to Gson Like this
Gson gson = new GsonBuilder()
.registerTypeAdapter(Data.class, new DataSerializer())
.create();

Remove duplication from an array of objects

I have an object like below,
class LocationData{
String time;
String name;
String address;
}
for this object i have created getter setter.
By using service i fill this above model and save into room database.
whenever user open my app i just update the room database data to server using API.
Now sometimes the time duplication occurred. How to remove the object from array based on time. time should be unique.
You can use the extension function distinctBy. If you have an array of LocationData objects called allLocations it would be
val distinctLocations = allLocations.distinctBy { it.time }
Note distinctLocations will be a List; if you want it to be an array, use toTypedArray()

JSONObject as class attribute storage/retrieval

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.

how to link my getEmptyForeignCollection() object with my parent object?

I want to persist an object with two foreignCollections.
But when I try to query the object, my foreignId is always null.
I already read this answers but it doesn't really help me: Collections in ORMLite
VOPerception perception = new VOPerception();
perception.setOrientation(daoOrientation.createIfNotExists(
orientationLocalizer.getCurrentOrientation()));
ForeignCollection<VOAccessPoint> fAp =
daoPerception.getEmptyForeignCollection("accessPoints");
fAp.addAll(wifiLocalizer.getCurrentScanResultMap());
perception.setAccessPoints(fAp);
daoPerception.create(perception);
List<VOPerception> list = daoPerception.queryForAll();
here data are correctly stored but VOAccessPoint objects have no link with the parent VOPerception object.
Here are my two classes:
public class VOPerception {
#DatabaseField(generatedId=true)
private int per_id;
#ForeignCollectionField(eager=true)
ForeignCollection<VOAccessPoint> accessPoints;
...
}
public class VOAccessPoint{
#DatabaseField(generatedId=true)
private int ap_id;
#DatabaseField(foreign=true,columnName="apForeignPerception_id")
private VOPerception apForeignPerception;
...
}
Your queryForAll() is returning no objects because none of your VOAccessPoint instances ever set their apForeignPerception field to be perception. Adding the VOAccessPoint objects using the ForeignCollection added them to the DAO but did not automagically assign their apForeignPerception field.
You should do something like:
...
Collection<VOAccessPoint> points = wifiLocalizer.getCurrentScanResultMap();
for (VOAccessPoint point : points) {
point.setApForeignPerception(perception);
}
fAp.addAll(points);
...
I can see how you might think that this would be handled automagically but at the time they are added to the ForeignCollection, the perception is not even assigned. I suspect that there is a missing feature for ORMLite here or at least a better exception.
I would recommend to use assignEmptyForeignCollection(Obj parent, fieldName). This will create a new foreign collection and all objects you will add via add(Obj element) will have the parent value set automatically.

In struts2 how can i get request parameter from android

In android i wrote a program that sends a string value to a servlet post method.
in the servlet, by using request.getParameter() i can receive the data.
Is the same applied to struts2? how to get the request parameter string in struts2 or anyother way to obtain the request parameter string.
You would create a variable in your action and then supply a public setter for it. If you need to expose the variable to a view (JSP page), then you will also want to provide a getter.
For example:
private String myValue;
public void setMyValue(final String myValue) {
this.myValue = myValue;
}
Then just pass the variable to the URL for the action. e.g., http://yoursite.com/youraction?myValue=easy
Struts will automatically invoke the setter and pass the value of the form parameter.

Categories

Resources