Convert a custom Object to JSON in Totalcross

Asked

Viewed 65 times

1

It is possible to serialize a Custom Object for JSON without having to insert field-by-field, for example:

JSONObject jsonObject = new JSONObject();                       
jsonObject.put("id", meuObjeto.id);
jsonObject.put("dt_sync", meuObjeto.dtSync);
jsonObject.put("dt_modif", meuObjeto.dtModif);

I tried to pass the object by parameter in the Jsonobject constructor

JSONObject jsonPedido = new JSONObject(pedido);

But some values are lost.

In Java, Android etc.. it is possible to use lib JACKSON for example to generate an Object Map and convert it to a JSON... Or via Annotations.. Anyway..

There is a more agile way to implement this Custom Object serialization for a Jsonobject in Totalcross?

  • This constructor expects there to be getters in the object being serialized. It has how to share a complete, verifiable and minimal example?

  • This comment already explains the failure of the attempt by using the Jsonobject constructor. For our false-POJOS have no getters and setters methods..

  • Just in case.. isn’t there a class that does the opposite of Jsonfactory? Convert a Java Object to Json Object? In this case it would be through the constructor, as it would use getters methods through Reflection to popular a Json Object.. that?

  • So it doesn’t work for serialization via the JSONObject.

1 answer

1

I don’t know if you still need a solution, but I managed to do it this way:

public class AuthenticationDTO {

private String username;

private String password;

public AuthenticationDTO() {
}

public AuthenticationDTO(final String username, final String password) {
super();
this.username = username;
this.password = password;
}

public String getUsername() {
return username;
}

public String getPassword() {
return password;
}    

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

@Override
public String toString() {
return "AuthenticationDTO [username=" + username + ", password=" + password + "]";
}
}

Using Jsonobject, it converted my object to JSON:

AuthenticationDTO authenticationDTO = new AuthenticationDTO("admin", "admin");
JSONObject requestJsonAutentication = new JSONObject(authenticationDTO);
System.out.println(authenticationDTO.toString());

Returning my JSON: {"password":"admin","username":"admin"} I believe that the "_" may be influencing when converting, or the fields of your object are not with the correct names.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.