convert enum as singleton to JSON using gson - java

I have singleton implementation of enum as below :
public enum DeviceDetail{
INSTANCE;
private Context context = null;
private int handlercheck = 0;
private String network = "";
private String deviceInfo = "NoData";
private String androidVersion = "";
private String appVersion = "";
private String appName = "";
private String deviceID;
private String deviceinfo;
public void initilize(){
// deviceInfo = getDeviceInfo();
networktype = getNetworktype(context);
deviceID = getDeviceID(context);
//androidVersion = getAndroidVersion();
appVersion = getAppVersion(context);
appName = getAppName(context);
}
DeviceDetail(){
deviceInfo = getDeviceInfo();
androidVersion = getAndroidVersion();
initilize();
}
public static DeviceDetail getInstance() {
return DeviceDetail.INSTANCE;
}
}
I want to convert this DeviceDetail to JSON using GSON, for that I have written
public static String convertObjectToJsonString(DeviceDetail deviceData) {
Gson gson = new Gson();
return gson.toJson(deviceData);
}
I am calling this method as
convertObjectToJsonString(DeviceDetail.INSTANCE)
but it only returns me the string "INSTANCE" not key value pairs as it does for objects. Suggest the changes need to be made so that I get string with all fields in enum in key value JSON.

I have ended up in using a not so elegant workaround as below :
public static String convertObjectToJsonString(DeviceDetail deviceData) {
// Gson gson = new Gson();
// GsonBuilder gb = new GsonBuilder();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("androidVersion", deviceData.getAndroidVersion());
jsonObject.addProperty("appName", deviceData.getAppName());
jsonObject.addProperty("appVersion", deviceData.getAppVersion());
jsonObject.addProperty("networkType", deviceData.getNetworktype());
jsonObject.addProperty("deviceInfo", deviceData.getDeviceInfo());
jsonObject.addProperty("deviceID", deviceData.getDeviceID());
jsonObject.addProperty("city", deviceData.getCity());
jsonObject.addProperty("country", deviceData.getCountry());
//jsonObject.addProperty("appName",deviceData.getAppName());
return jsonObject.toString();
}

Related

Getting a substring from a larger substring

I have this as a substring. It is a JSON string. I am trying to get the id string from it. I was able to do this by using two indexOf's and then substring the two indexOf's. What is a better solution.
Here is my string
"{"id":"762c094a-4b65-499e-b5b2-de34ef8d726e","createdTimestamp":1605558195131,"username":"sssdv","enabled":false,"totp":false,"emailVerified":false,"firstName":"cdf","lastName":"dddz","email":"hgddf#fdaddf.com","disableableCredentialTypes":[],"requiredActions":[],"notBefore":0,"access":{"manageGroupMembership":true,"view":true,"mapRoles":true,"impersonate":true,"manage":true}}"
And here is my code.
int id = results.indexOf("id");
int cr = results.indexOf("createdTimestamp");
String strId = results.substring(id + 5, cr - 3);
A better solution is to use an actual JSON parser. There are plenty out there. Take a look at this answer on a different question. I would suggest using Gson:
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
JsonElement element = gson.fromJson(json, JsonElement.class); // Parse it
String id = element.getAsJsonObject().get("id").getAsString(); // Get your desired element
System.out.println(id);
An even better solution would be to create a class with the fields from your JSON and parse the JSON string to that class:
public class MyObject {
// The names and types of these fields must match the ones in your JSON string
private String id, username, firstName, lastName, email;
private long createdTimestamp;
private boolean enabled, totp, emailVerified;
private String[] disableableCredentialTypes, requiredActions;
private int notBefore;
private Access access;
public String getId() {
return id;
}
// Other getters and setters...
private static class Access {
private boolean manageGroupMembership, view, mapRoles, impersonate, manage;
// ...
}
public static void main(String[] args) throws IOException {
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
MyObject object = gson.fromJson(json, MyObject.class); // Parse the string to your data type
System.out.println(object.getId()); // Print the id
}
}
String results = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
String[] parts = results.split("\"");
System.out.println(parts[3]); //gives the id, every time

GSON toJson() method returns null for a POJO

This is my POJO class
public class ResourceRecord {
public ResourceRecord() {}
public String name;
public Integer ttl;
public String type;
public String rr;
#SerializedName("class")
public String dnsClass;
}
And this the serialisation:
ResourceRecord rr = new ResourceRecord() {
{
name = "8.8.8.8";
dnsClass = "IN";
ttl = 600;
rr = "0431shangmao.com.";
type = "A";
}
};
String rrStr = new Gson().toJson(rr);
Apparently, rrStr gets null. Why?
I tried annotating the fields with #Expose but the result stayed the same.
UPDATE:
I changed to constructing to:
ResourceRecord rr = new ResourceRecord("8.8.8.8", 900,"A","1.dnstest.netshade.net.", "IN");
and it worked.
The reason why it didn't work is because you were creating anonymous innerclass of ResourceRecord when you instantiate using curly braces:
ResourceRecord rr = new ResourceRecord() {
{
name = "8.8.8.8";
dnsClass = "IN";
ttl = 600;
rr = "0431shangmao.com.";
type = "A";
}
};
And Gson doesn't support serializing anonymous subclasses.
Try this,
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);
obj is the object of pojo class

How to right declare a composite java JSON object from string?

i have this string which i'm using for testing of api:
{"limit":30, "offset":"0", "filters": [{"property":"vlc.vlc","operator":"=","value":"DEKU113829"}]}
I would like to create JSOn object for processing in Android app using the:
JSONObject json = new JSONObject();
json.put("limit", 30);
json.put("offset", "0");
But i don't know how to create "filters" section using put method...
What is the right and most effective solution for this?
JSONObject/JSONArray supports a "builder-esque" pattern and put can be chained - it will return the same (but modified) object.
JSONObject json =
new JSONObject()
.put("limit", 30)
.put("offset", "0") /* but should be 0? */
.put("filters",
new JSONArray()
.put(new JSONObject()
.put("property", "vlc.vlc")
.put("operator", "=")
.put("value", "DEKU113829")
)
);
Alternatively, look into a POJO mapper like Gson, which I would recommend overall for ease of use and consistency.
Try this...
JSONObject json = new JSONObject();
json.put("limit", 30);
json.put("offset", "0");
JSONArray js_array = new JSONArray();
JSONObject json_obj = new JSONObject();
json_obj.put("property", "vlc.vlc");
json_obj.put("operator", "=");
json_obj.put("value", "DEKU113829");
js_array.put(json_obj);
json.put("filters",js_array);
Use the Gson Library. Your model objects for the JSON will be
public class MainModel
{
private int limit ;
public int getlimit()
{
return this.limit;
}
public void setlimit(int limit)
{
this.limit = limit;
}
private String offset ;
public String getoffset()
{
return this.offset;
}
public void setoffset(String offset)
{
this.offset = offset;
}
private ArrayList<Filter> filters ;
public ArrayList<Filter> getfilters()
{
return this.filters;
}
public void setfilters(ArrayList<Filter> filters)
{
this.filters = filters;
}
}
public class Filter
{
private String property ;
public String getproperty()
{
return this.property;
}
public void setproperty(String property)
{
this.property = property;
}
private String operator ;
public String getoperator()
{
return this.operator;
}
public void setoperator(String operator)
{
this.operator = operator;
}
private String value ;
public String getvalue()
{
return this.value;
}
public void setvalue(String value)
{
this.value = value;
}
}
You can populate your filter object and create MainModel object and add the filter object to it. Next use Gson library as below to get your json string
Gson gsonParser = new Gson();
String jsonString = gsonParser.toJson(mainModelObject);

Json string to java object

I'm having following class
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public Result OperationResult;
public String Messages;
public String UpdateAvailable;
public Object ResultData;
}
I'm having json string like,
{"OperationResult":0,"Messages":"","UpdateAvailable":"","ResultData":{"SessionId":"3b44a524-fc2a-499b-a16e-6d96339a6b5b","UserName":"admin","AccoundId":null,"Roles":["Administrator"],"DisplayName":"Admin","Status":3,"Type":1}}
I want to assign this json string to above class.I'm using GSON for assign json string to java object.In normal class i can assign json string to java object. But for this class i couldn't assign directly. Please any one help me,
Now i'm assigning like,
String formatedjsonstring = {json string};
Log.i("FORMAT STRING:",formatedjsonstring);
Gson gson = new Gson();
ReturnData returndata = (ReturnData) gson.fromJson(
formatedjsonstring, ReturnData.class);
You could use JavaJson from sourceforge. You could pass your json string to JsonObject .parse().
Try this
JsonObject json = JsonObject .parse("{\"OperationResult\":0, \"Messages\":\"UpdateAvailable\"");
System.out.println("OperationResult=" + json.get("OperationResult"));
System.out.println("Messages=" + json.get("Messages"));
https://sourceforge.net/projects/javajson/
Since your Java class doesn't resemble your JSON in any way, shape or form ... you're going to have a problem with that.
Problem #1: OperationResult should be an int
Problem #2: You're declared ResultData as an Object ... Java doesn't work like that.
You need your POJO to match the JSON:
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public int OperationResult;
public String Messages;
public String UpdateAvailable;
public MyResultData ResultData;
}
class MyResultData {
public String SessionId;
public String UserName;
public String AccountId;
public List<String> Roles;
public String DisplayName;
public int Status;
public int Type;
}
ReturnData rd = new Gson().fromJson(jsonString, ReturnData.class);
I'd also consider using Gson's #SerializedName("name") annotation to convert the PascalCase field names in your JSON to camelCase field names in Java.
#SerializedName("OperationResult") public int operationResult;
Try this:
java.lang.reflect.Type type = new TypeToken<ReturnData>(){}.getType();
ReturnData rd = new Gson().fromJson(jsonString, type);

Parsing JSON array with a sub-array with GSON?

Say I have a JSON string like:
{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"200"}, ...
My accessor:
import com.google.gson.annotations.SerializedName;
public class accessorClass {
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("image")
private String image;
// how do I place the sub-arrays for the image here?
...
public final String get_title() {
return this.title;
}
public final String get_url() {
return this.url;
}
public final String get_image() {
return this.image;
}
...
}
And my main:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jstring).getAsJsonArray();
ArrayList<accessorClass > aens = new ArrayList<accessorClass >();
for(JsonElement obj : Jarray )
{
accessorClass ens = gson.fromJson( obj , accessorClass .class);
aens.add(ens);
}
What do you think would be the best way to get those sub-arrays for the image here?
FYI if your JSON is an array: {"results:":[{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}
Then you need a wrapper class:
class WebServiceResult {
public List<AccessorClass> results;
}
If your JSON isn't formatted like that, then your For loop you created will do it, (if not a little clunky, would be better if your JSON is formed like above).
Create an Image class
class ImageClass {
private String url;
private int width;
private int height;
// Getters and setters
}
Then change your AccessorClass
#SerializedName("image")
private ImageClass image;
// Getter and setter
Then GSON the incoming String
Gson gson = new Gson();
AccessorClass object = gson.fromJson(result, AccessorClass.class);
Job done.

Categories