Representing request array in Java - java

I have the following request
{
"attachments":[
{
"fields":[
{
"value":"Testing value"
}
]
}
],
"channel":"testing",
"value":"Testing value"
}
and want to make it as a request in Java, but I am struggling how to represent it and use it. So far I've done this
public class RequestTest {
ArrayList<ArrayList<String>> attachments = new ArrayList<ArrayList<String>>();
ArrayList<String> fields = new ArrayList<String>();
private String channel;
private String value;
}
But I am not sure how to put the value and how to call it after that.

You have to create an object structure like:
public class RequestTest {
ArrayList<Attachment> attachments = new ArrayList<>();
private String channel;
private String value;
}
public class Attachement {
ArrayList<Field> fields = new ArrayList<>();
}
public class Field {
String value;
}
Then you can use jackson or gson to create the json string you expect.

If you want to present the request in Java class, then you should create a class named "Field" and class named "Attachment".
public class Field{
private String value;
}
public class Attachment{
private List<Field> fields;
}
public class RequestTest{
private List<Attachment> attachments;
private String channel;
private String value;
}
If you want to present it with JsonObject, you can refer to JsonObject

Related

How to migrate Room database with ArrayList field?

There is an already created #Embedded class Player. I want to add to it the ArrayList field, which uses #TypeConverters, which converts my List to Gson when saving and back when loading.
Please tell me how to make a request in the void migrate ()
method to add the list to an already existing instance of the Player
class.
#Database(entities = {Save.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(final SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE Save ADD COLUMN trainingPower
INTEGER DEFAULT 5 NOT NULL");
}
};
}
Player class:
public class Player
{
#TypeConverters({AlbumsListConverter.class})
private List<Albums> albumsList = new ArrayList();
#Embedded(prefix="energy_")
public Skills energy;
public int energyCount;
public int energyMax = 50;
public String fameName;
#Embedded(prefix="flow_")
public Skills flow;
public int imageID;
int imagePers;
#Embedded(prefix="mast_")
public Skills mastering;
#Embedded(prefix="mast2_")
public Skills mastering2;
private long money = 50;
#Embedded(prefix="music_")
public Skills music;
private String name;
public int ratingPosition = 1;
public int reclameToken = 0;
#TypeConverters({TrackListConverter.class})
public List<Tracks> releaseList = new ArrayList();
#TypeConverters({MessagesConverter.class})
public List<Massages> messagesList = new ArrayList<>();
private long reputation = 0;
private int respect = 1;
...
}
class Save:
#Entity
public class Save
{
#TypeConverters({ArrayConverter.class})
public String[] AllTopicTracks;
#Embedded
private Player actor;
...
}
TypeConverter:
public class MessagesConverter {
#TypeConverter
public String fromMassagesList(List<Messages> messages)
{
Gson gson = new Gson();
return gson.toJson(messages);
}
#TypeConverter
public List<Messages>toMessagesList(String data)
{
Gson gson = new Gson();
Type type = new TypeToken<List<Messages>>(){}.getType();
return gson.fromJson(data,type);
}
}
It seems you had used #Embedded for multiple variables. If #Embedded is annotated the variables of model class is treated as column for the same table. So for the case of multiple objects of same type you shoud use TypeConverter where the object can be converted to json string while saving and later retrieved as the object.
Instead of making embedded Player, create type converter for player and use it. By doing this you don't have to create separate type converter for objects inside player.

private class ArrayList (set)

I have a class named "classroom" and i want send one arraylist with classroom.setMaterias(Arraylist). Is this code:
Class Clasroom
public class Aula implements java.io.Serializable {
private String nombre;
private String grupo;
private int tutor;
ArrayList<String> materias = new ArrayList<String>(); // ¿How create arraylist?
public Aula() {
// Constructor
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
I would like to know if I could, for example, send an "arraylist" through a SET and then make the "arraylist" that I created previously in my class "classroom" be exactly the same
I would not know how to create the arraylist, or the set or get methods. Can you help me please?
PD: This is the JSON ARRAY i talking about:
if (obj.has("materias")) {
JSONArray materias = obj.getJSONArray("materias");
datos.setArrayList(materias);
// System.out.println(materias); // ["DWES","DWEC","IW","DAW","IE"]
Class Clasroom
public class Aula implements java.io.Serializable {
private String nombre;
private String grupo;
private int tutor;
ArrayList<String> materias; // ¿How create arraylist?
public Aula() {
// Constructor
this.setArrayList(new ArrayList<>()); //Here you initialize the arraylist when you create an instance of this class.
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
//Here are the getters and setters.
public ArrayList<String> getList(){
return this.materias;
}
private void setArrayList(ArrayList<String> list){
this.materias = list;
}
The proper way of doing it is using getters and setters and using List interface rather than ArrayList<> directly.
List<String> materias = Collections.emptyList();
public Aula() {
// Constructor
}
public List<String> getMaterias() {
return materias;
}
public void setMaterias(List<String> materias ) {
this.materias = materias ;
}
public void addMaterias(String materia) {
materias.add(materia);
}
You can have additional addMaterias() method to add entries to your List.
public class Aula implements java.io.Serializable {
private List<String> materia = new ArrayList<>();
...
public void setMateria1(final List<String> aMateria) {
this.materia = aMateria;
}
public void setMateria2(final List<String> aMateria) {
this.materia.clean();
this.materia.addAll(aMateria);
}
}
setMateria1() replaces the list with the given argument, thus any changes (EG deletion of items,) made later to the one, is reflected in the other.
While setMateria2() copies the argument's items, thus deletion or insertion to any of them does not change the other one.
Also ArrayList is a concrete implementation of the interface List. It is preferable to declare variables as the base class or interface, instead of a concrete implementation.
public class Aula implements java.io.Serializable {
ArrayList<String> materias = new ArrayList<String>();
...
public ArrayList<String> getMaterias(){
return materias;
}
public void setMaterias(JSONList materias) throws JSONException {
materias.clear();
for(int i=0;i<materias.length();i++)
this.materias.add(materias.getString(i));
}
}
And put the exact same code into the classroom class.
Second way is to set the Lists in the constructor:
public class Aula implements java.io.Serializable {
ArrayList<String> materias = new ArrayLis<>();
...
public Aula(JSONList materias) throws JSONException {
for(int i=0;i<materias.length();i++)
this.materias.add(materias.getString(i));
}
public ArrayList<String> getMaterias(){
return materias;
}
}
Again same for classroom. And than you create them eg.
Aula aula = new Aula(materias);
Classroom classroom = new Classroom(materias);
This is assuming you have Strings in your list. Otherwise it depends on your data in the list.
If it contains other Lists it they need to be merged or skipped and so on...
If the json is not all Strings(e.g. has Sublists and Objects) and it should match the actual structure of your json I'd need that structure too and most probably an Arraylist of Strings might be the wrong Container for such a json - tree.
btw. better change classroom to Classroom(capital C for the classname) ...

Java how to generate and assign attributes to an Object in an efficient way?

I'm building an automation testing program, I'd like it to have ability to generator fake customer data. To do that, I've done things like:
- Created a Customer Object which has 40 variables
- Created a GustGenerator Class to generate faker data and assign to Customer object.
//Customer object class
public class Customer {
public static final String EMAIL = "user.name#******.com";
public static final String PHONE = "0956***2001";
public static final String LAS_NAME = "Owen";
public static final String FIN_PURP_TYPE = "ELP";
public static final String ADDRESS = "User Address";
private String title;
private String firName;
private String midName;
private boolean isReqMet;
private int media;
...... 40 attributes in total.
...... getters and setters
}
//Fake customer data generator.
public class CustGenerator {
private Customer customer;
private Faker faker = new Faker();
private Customer firstName(Customer customer) {
customer.setFirName(faker.name().firstName());
return customer;
}
private Customer midName(Customer customer) {
customer.setMidName(faker.name().lastName());
return customer;
}
......Generate data one by one.
}
My question is is there a better way to construct this feature? More simple and more efficiency. Any input is appreciated. Thank you very much.
You can do it by creating a constructer function in your customer class:-
Public class Customer{
...create variables
Public Customer(bool random){
If(random){
//generate variables randomly
}else{
//initiallize what do you want
}
}
}
And also i suggest if parameters is such more create a dictionary instead of creating a lot of variables, for e.g:-
Dictionary<string, object> vals = new Dictionary<string, object>();
And if you just use string values so make second parameter to string.

Object to string delimited format

I have set of objects of different types.
Ex : Employee emp, adress adr
These two classes have list of properties
public class Employee{
private Stringname;
private int age;
}
public class Adress {
private String HouseNo;
private string Street;
private string pin;
}
Each attribute is assigned with some 2 character value
Name (NA), age (AG), HouseNo(HN),Street(ST), pin(PN)
I need to construct a string with these data and delimit with a %
Output:
NA%Vidhya%AG%30%HN%80%ST%1st cross%PN%100100
Each class knows it own data best so I would let each class be responsible for generating the string. As I understand it the two char codes for each field are unique for each class and member and only used when generating the string so only the class would need them.
interface AttributeDescription {
String generateDescription();
}
public class Employee implements AttributeDescription {
//members...
public String generateDescription() {
return String.format(“NA%%%s%%AG%%%d”, name, age)
}
Then simply call this method for all objects implementing the interface.
AttributeDescription object = ...
String attr = object.generateDescription();
I don't think it can be generalized more than this given the requirements.
Update
It might be better to have a builder class for building the string to get a more unified behavior between classes. Here is an example
public class AttributeBuilder {
private builder = new StringBuilder();
public String getAttribute() {
return builder.toString();
}
public void add(String code, String value) {
if (value == null) {
return;
}
builder.append(code);
builder.append(‘%’);
builder.append(value);
builder.append(‘%’);
}
}
And then you would also have to implement add(...) methods for other data types in a similar fashion. The builder could then be used like
public String generateDescription() {
AttributeBuilder builder = new AttributeBuilder();
builder.add(“NA”, name);
builder.add(“AG”, age);
return builder.getAttribute();
}

JSON to java object returing LinkedHashMap

I have below json string :-
{"name":"Test","sortlist":[],"filterlist":[{"fieldname":"regions_id","operator":"equals","value":{"id":1,"code":"HIGH","description":"HIGH Region","comment":"High Region","active":true}}]}
and Java class as below :-
#JsonSerialize
#JsonDeserialize
public class ItemFilter implements Serializable {
private String name;
private List<FieldFilter> filterlist = new ArrayList<FieldFilter>();
}
public class FieldFilter implements Serializable {
private static final long serialVersionUID = 1L;
private String fieldname;
private String operator;
private Object value;
}
and my convert method as below :-
public static ItemFilter convertItemFilter(String item) {
ObjectMapper mapper = new ObjectMapper();
try {
ItemFilter itemFilter = mapper.readValue(item, new TypeReference<ItemFilter>(){});
return itemFilter;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
ItemFilter domain is getting converted correctly but in private Object value; field i am getting LinkedHashMap i want to get an simple object and later i will type cast it.
Can someone please guide me how to escape LinkedHashMap and get an simple Java Object in variable?
i cant use hard coding Object type because its a generic pojo which can have any object type. hard coding will make this pojo very bigger and frontend also need to change for it. So that why i have used Object as data type.
The following class structure should return the JSON to "YourObject"
public class YourObject{
private String name;
private List<String> sortList;
private List<Filter> filterList;
public static class Filter{
private String fieldname;
private String operator;
private Value value;
}
public static class Value{
private Integer id;
private String code;
private String description;
private String comment;
private Boolean active;
}
}
Then use the following to read it into the object:
YourObject itemFilter = mapper.readValue(item, YourObject.class);

Categories