Convert class into a JSONObject - java

I have several classes like this. I want to convert the classes into JSONObject format.
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("id")
private Integer mId;
#SerializedName("name")
private String mName = "";
#SerializedName("email")
private String mEmail;
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
}
I know that I can convert these classes to JSONObject format as follows:
User user = new User();
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", user.getId());
jsonObj.put("name", user.getName());
jsonObj.put("email", user.getEmail());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is that I need to do this for a lot of different classes that are much longer than this across a lot of files. Can I use GSON to fill the JSONObject from myClass so that I don't need to edit every time the class structure changes?
The following returns a JSON string but I need it as an Object as when I send it to the system that sends the requests via a REST API it sends with unwanted quotation marks.
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
When I use this in another JSON builder that asks for an Object I get
{"request":"{"id":"100","name":"Test Name","email":"test#example.com"}"}
When I want
{"request":{"id":"100","name":"Test Name","email":"test#example.com"}}

I found that the following works with GSON:
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is not type safe, however.

Here is a crude example you can use to use Reflection to build the JSONObject..
Warning it's not pretty and does not contain really type-safety.
public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
JSONObject object = new JSONObject();
Class<?> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof SerializedName){
SerializedName myAnnotation = (SerializedName) annotation;
String name = myAnnotation.value();
Object value = field.get(obj);
if(value == null)
value = new String("");
object.put(name, value);
}
}
}
return object;
}
Here is an example usage:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
Output
{
"id": "",
"name": "",
"email": ""
}

Try with this code:
// Returns the JSON in a String
public String getJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
// Builds the Model Object from the JSON String
MyModel model =new MyModel();
JSONObject j = new JSONObject(model.getJSON());

Related

Java convert Java object to Json object

I can not convert Java object to JSON object this is my main java object :
I do this:
public class LoginDao {
String company;
String user;
String secure_password;
String secure_device_id;
app_info app_info;
}
jsonObject.put("company", company);
jsonObject.put("user", user);
jsonObject.put("os", os);
jsonObject.put("ver", ver);
jsonObject.put("lang", lang);
but on output I do not have this :
{
"company":"",
"user":"test",
"secure_password":"",
"secure_device_id":"",
"app_info":
{
"os":"soapui",
"ver":1,
"lang":"pl"
}
}
You can do this in many more way. Here are given bellow:
Using Google Gson:
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Java code:
LoginDao loginData;
// Here loginData is the object. ...
Gson gson = new Gson();
String json = gson.toJson(loginData);
Using Jackson:
Gradle Dependency:
compile 'com.fasterxml.jackson.core:jackson-databind:2.5.3'
Java code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(loginData);
If you need above output, try this:
JSONObject obj = new JSONObject();
obj.put("company", company);
obj.put("user", user);
obj.put("secure_password", secure_password);
obj.put("secure_device_id", secure_device_id);
JSONObject anothetObj = new JSONObject();
anothetObj.put("os", os);
anothetObj.put("ver", ver);
anothetObj.put("lang", lang);
obj.put("app_info", anothetObj);
You can create two DAO Classes,
public class LoginDAO {
private String company;
private String user;
private String secure_password;
private String secure_device_id;
// Getter Methods
public String getCompany() {
return company;
}
public String getUser() {
return user;
}
public String getSecure_password() {
return secure_password;
}
public String getSecure_device_id() {
return secure_device_id;
}
// Setter Methods
public void setCompany( String company ) {
this.company = company;
}
public void setUser( String user ) {
this.user = user;
}
public void setSecure_password( String secure_password ) {
this.secure_password = secure_password;
}
public void setSecure_device_id( String secure_device_id ) {
this.secure_device_id = secure_device_id;
}
}
public class App_info {
private String os;
private float ver;
private String lang;
// Getter Methods
public String getOs() {
return os;
}
public float getVer() {
return ver;
}
public String getLang() {
return lang;
}
// Setter Methods
public void setOs( String os ) {
this.os = os;
}
public void setVer( float ver ) {
this.ver = ver;
}
public void setLang( String lang ) {
this.lang = lang;
}
}
An then you can do this,
LoginDAO login = new LoginDAO();
App_info app = new App_info();
JSONObject jo = new JSONObject();
jo.put("company", login.getCompany());
jo.put("user", login.getUser());
jo.put("secure_password", login.getSecure_password());
jo.put("secure_device_id", login.getSecure_device_id());
Map m = new LinkedHashMap(3);
m.put("os", app.getOs());
m.put("ver", app.getVer());
m.put("lang", app.getLang());
jo.put("app_info", m);
System.out.println(jo.toString);
If not you can simply do this,
JSONObject jo = new JSONObject(
"{ \"company\":\"\", \"user\":\"test\", \"secure_password\":\"\", \"secure_device_id\":\"\", \"app_info\": { \"os\":\"soapui\", \"ver\":1, \"lang\":\"pl\" } }"
);

Android Studio - Issue loading JSON

I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'

Issue in getting the individual data parameters from the json.JsonArray

I am receiving the data from the api but the code following do not work for some reason
Here is the code:
ListeningExecutorService service = MoreExecutors.listeningDecorator(newFixedThreadPool(50));
final ListenableFuture<JsonElement> userfromapi = mClient.invokeApi("userinfo",null, "GET", null);
Futures.addCallback(userfromapi, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(final JsonElement result) {
final JsonArray contacts = result.getAsJsonArray();
final String jsonString = contacts.getAsJsonObject().get("id").getAsJsonPrimitive().getAsString();
final String facebookid = contacts.getAsJsonObject().getAsJsonPrimitive("id").getAsString();
final String name = contacts.getAsJsonObject().getAsJsonArray("first_name" + "last_name").toString();
final String imgurl = "https://graph.facebook.com/" + facebookid + "/picture";
}
The problem is that, after the success call back getting the individual ids, name, etc
Make model class- For e.g
public class MyClass{
#SerializedName("Name")
private String Name;
public String getName() {
return Name;
}
}
for e.g Fetch data like this -
JSONObject jsonObject = new JSONObject(response);
MyClass myClassModel = new Gson().
fromJson(jsonObject.get("JsonArrayName").toString(),
new TypeToken<MyClass>() {
}.getType());

Android fetch volley data from a string of arrays

AM sending a request using android volley and get a response like this
public void onResponse(JSONObject response
try {
String responsedata = response.getString("data");
Log.i("test",responsedata);
} catch (JSONException e) {
e.printStackTrace();
}
}
The above log prints
[{"id":1,"identifier":"TYam Plant","header_val":"tyamplant"},
{"id":2,"identifier":"Touron Plant","header_val":"toroun"}
]
Now i would like to loop through these and extract an array of individual properties that is
id, identifier, header_val
How do i go about this. Am still new to java
You response is JSONArray not JSONObject check it
You need to use JSONArray request instead of JSONObject request of volley
Try this to parse your json
try {
JSONArray jsonArray= new JSONArray(responsedata);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
}
} catch (JSONException e) {
e.printStackTrace();
}
Better to Parse your JSON Using google-gson-library
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of
EXAMPLE : How to Parse JSON Array with Gson
You create a Custom Object with 3 field: id, identifier,header_val
public class YourObject {
private String id;
private String identifier;
private String header_val;
public YourObject(String id, String identifier, String header_val) {
this.id = id;
this.identifier = identifier;
this.header_val = header_val;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getHeader_val() {
return header_val;
}
public void setHeader_val(String header_val) {
this.header_val = header_val;
}
}
Loop and add into list: List<YourObject> yourList = new ArrayList<>();
try {
JSONArray jsonArray= new JSONArray(responseString);
for (int i=0; i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
yourList.add(new YourObject(id, identifier, header_val);
}
} catch (JSONException e) {
e.printStackTrace();
}

Create "tagged" Json Object, instead of just properties

I'm having some problems when i try to deserialize my object into a json string.
I'm getting the following object:
{
"idUser": 1,
"name": "2",
...
}
But I want to achieve this object:
{
"user": {
"idUser": 1,
"name": "2",
...
}
}
I'm serializing my object using this code:
public static String deserializeUser(User user){
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
try {
json = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
I'm using the api com.fasterxml.jackson
And here goes my User class:
public class User {
public long idUser;
public String name;
public String email;
public String phoneNumber;
#JsonProperty("cpf")
public String CPF;
public String password;
public boolean active;
private String facebookPictureUrl;
private String cameraTakenPhotoBase64;
private String facebookUserId;
... (constructor and getters/setters)
}
That is because you're serializing an instance of User. The intended JSON matches a map with a user property. So you could achieve it with:
Map<String, User> userMap = new HashMap<String, User>();
userMap.put("user", user);
String json = "";
try {
json = objectMapper.writeValueAsString(userMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

Categories

Resources