Java Android Gson convert boolean to int from response server - java

Help me, guys!
Please, advise a simple solution to convert type boolean from server to int in Android :)
When I log in, i get respone from server like this :
{"status":{"error":0,"code":200,"message":"OK"},"response":{"profile":{"id":114,"username":"k#gmail.com","full_name":"k","phone":"9999999","verified":1,"admin":0,"allow_dev":false,"company":{"id":9,"name":"ООО \"Фингерз медиа\"","email":"info#fingers.by","sample":null,"logo":"http://storage.guardian-glass.fingersmedia.by/0cb56968b3cec1bba301db8d51d1015e.jpg"}},"access_token":"15629e234e04a54a5a44ef2aa4eccb1d"}}
Then I get undefined exception: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected NUMBER but was BOOLEAN
This happens because of JsonElement "allow_dev" is boolean from server, and in Android I have "allow_dev" like int.
This is login method :
private void login(String email, String pass) {
showProgress();
JsonObject params = new JsonObject();
params.addProperty("username", email);
params.addProperty("password", pass);
UserOperationsTask task = new UserOperationsTask(UserOperationsTask.TaskMode.MODE_LOGIN, params) {
#Override
public void onLoadFinished(Bundle res) {
hideProgress();
String errorMessage = res.getString(UserOperationsTask.RESULT_ERROR_STRING);
if (errorMessage != null) {
showMessage(getString(R.string.login_error), getString(R.string.server_request_error));
} else {
String json = res.getString(UserOperationsTask.RESULT_JSON_STRING);
if (json != null) {
JsonParser parser = new JsonParser();
JsonObject responseData = parser.parse(json).getAsJsonObject();
JsonObject companyObj = responseData.getAsJsonObject("profile").getAsJsonObject("company");
}
setRegisteredMode();
}
}
};
task.execute(this);
}
This method parse response and I tried to convert allow_dev type from boolean to int, but I dont understand whether I'm doing right?
private Bundle parseProfileResponse(Context context, JsonObject responseData) {
Log.d(TAG, "parseProfileResponse");
// I tried convert allow_dev type from boolean to int
String allow_dev_server = String.valueOf(responseData.get("allow_dev"));
boolean b = allow_dev_server.equals("true");
int allow_dev = b ? 1 : 0; // true == 1
Profile profile;
profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class);
profile.allow_dev = allow_dev;
Bundle res = new Bundle();
res.putParcelable(RESULT_OBJ, profile);
res.putString(RESULT_JSON_STRING, responseData.toString());
try {
Cache.saveToCache(context, profile);
} catch (RemoteException e) {
Log.d(TAG, "parseAuthResponse RemoteException: " + e.toString());
res.putString(RESULT_ERROR_STRING, context.getString(R.string.database_error));
} catch (OperationApplicationException e) {
Log.d(TAG, "parseAuthResponse OperationApplicationException: " + e.toString());
res.putString(RESULT_ERROR_STRING, context.getString(R.string.database_error));
}
return res;
}
I have to get "allow_dev" convert it in int and write to database.

If you can switch to mappings, you can use everything static typing can give you, comparing to weakly "typed" JsonElement and its subclasses. It has several advantages: compile-time checking, more robust code, IDE support, etc. The major disadvantage is that you have to write custom mappings, however you there tools (online as well) that can try to generate simple mapping classes based on the given sample JSON (for example, a very popular tool here: http://www.jsonschema2pojo.org/).
Now, let's create some mappings. The mappings like the ones below are used rarely: final fields (used for "server responses" that are no supposed to be modified programmatically; Gson can assign such fields anyway); null for non-primitives and some hacks for primitive type defaults values to cheat the compiler (like Integer.value(0) but not simply 0: otherwise, javac may inline constants, thus Gson cannot affect them); no getters/setters (data-transfer objects are just data bags, but yes, getters can work better). Anyway, you can use your style, and the followings mappings are used for demonstration purposes (the mappings code has even compact formatting: one property per line collapsing the annotations).
final class Response<T> {
final Status status = null;
final T response = null;
}
final class Status {
final int error = Integer.valueOf(0);
final int code = Integer.valueOf(0);
final String message = null;
}
final class ProfileAndAccessToken {
final Profile profile = null;
#SerializedName("access_token") final String accessToken = null;
}
final class Profile {
final int id = Integer.valueOf(0);
final String username = null;
#SerializedName("full_name") final String fullName = null;
final String phone = null;
final int verified = Integer.valueOf(0);
final int admin = Integer.valueOf(0);
#SerializedName("allow_dev") #JsonAdapter(BooleanToIntTypeAdapter.class) final int allowDev = Integer.valueOf(0);
final Company company = null;
}
final class Company {
final int id = Integer.valueOf(0);
final String name = null;
final String email = null;
final String sample = null;
final URL logo = null;
}
Note two annotations above:
#SerializedName -- this annotation can "rename" fields so you can use even special characters (however it's discouraged, and it's typically used to map incoming JSON property names to javaCamelNamingConventions).
#JsonAdapter -- this annotation can "attach" a special type adapter to a certain field, so that it could convert JSON properties to the given field and vice versa.
Now let's implement a type adapter that can convert incoming boolean values to local int values and vice versa. Note that type adapters work in streaming manner, so you have to read JSON tokens stream on fly during read, and, of course, generate JSON tokens stream during write.
final class BooleanToIntTypeAdapter
extends TypeAdapter<Integer> {
// Public constructors may be evil, and let expose as less as possible
// Gson can still instantiate this type adapter itself
private BooleanToIntTypeAdapter() {
}
#Override
#SuppressWarnings("resource")
public void write(final JsonWriter out, final Integer value)
throws IOException {
// If the given value is null, we must write the `null` token to the output JSON tokens stream anyway in order not to break JSON documents
if ( value == null ) {
out.nullValue();
return;
}
// Let's assume that we can accept either 0 or 1 that are mapped to false and true respectively
switch ( value ) {
case 0:
out.value(false);
break;
case 1:
out.value(true);
break;
default:
// Or throw an exception as fast as we can
throw new IllegalArgumentException("Cannot convert " + value + " to a boolean literal");
}
}
#Override
public Integer read(final JsonReader in)
throws IOException {
// Peek the next token type, and if it's null, then return null value too
if ( in.peek() == NULL ) {
return null;
}
// Otherwise parse the next token as boolean and map it either to 1 or 0
return in.nextBoolean() ? 1 : 0;
}
}
That's all you need in Gson. Now, for you entire JSON, since the response mapping class is generic, you have to tell Gson what the T is. Gson accepts java.lang.reflect.Type in the fromJson method, and this type can hold both raw and parameterized types, so Gson could (de)serialize more accurately.
private static final Type profileAndAccessTokenResponse = new TypeToken<Response<ProfileAndAccessToken>>() {
}.getType();
final Response<ProfileAndAccessToken> response = gson.fromJson(JSON, profileAndAccessTokenResponse);
System.out.println(response.response.profile.allowDev);
System.out.println(gson.toJson(response, profileAndAccessTokenResponse));
Output:
0
{"status":{"error":0,"code":200,"message":"OK"},"response":{"profile":{"id":114,"username":"k#gmail.com","full_name":"k","phone":"9999999","verified":1,"admin":0,"allow_dev":false,"company":{"id":9,"name":"ООО \"Фингерз медиа\"","email":"info#fingers.by","logo":"http://storage.guardian-glass.fingersmedia.by/0cb56968b3cec1bba301db8d51d1015e.jpg"}},"access_token":"15629e234e04a54a5a44ef2aa4eccb1d"}}
Note that the first line is 0: this what is generated with BooleanToIntTypeAdapter. Backing to your code:
String allow_dev_server = String.valueOf(responseData.get("allow_dev"));
boolean b = allow_dev_server.equals("true");
int allow_dev = b ? 1 : 0; // true == 1
Profile profile;
profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class);
profile.allow_dev = allow_dev;
Can be replaced with simple:
final Profile profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class)
// now `Profile.allowDev` is 0 or 1 automatically
Note that responseData can be replace with a particular mapping, so you could even not parse at that line: probably you might simply pass the whole response object as a class mapping rather that JsonObject in your parseProfileResponse -- it would be more robust.

Related

is it possible to return "if condition satisfies return a list else return an error message" using a java method

I know that in Java a method can return only one return type... But if there is any possiblity to this, kindly let me know. From the below method I am trying to return a list if condition satisfies else i am trying to return an error message.
Here is my code:
#RequestMapping(value = "/getcompanies", method = RequestMethod.POST)
public List<CompanyMaster> getCompanies(#RequestBody UserDetails user) {
String OrgLoginId = user.getOrgLoginId();
String password = user.getuPassword();
String checkLoginId = null;
String uPassword = null;
String encPassword = null;
String loginId = null;
String checkAuthorized = null;
// String loginId=userService.getLoginId(OrgLoginId);
List<Object[]> CheckIdPassword = userService.checkLoginId(OrgLoginId);
List<Object[]> results = CheckIdPassword;
for (Object[] obj : results) {
checkLoginId = obj[0].toString();
if (null == obj[1]) {
uPassword = "";
} else {
uPassword = obj[1].toString();
}
loginId = obj[2].toString();
}
checkAuthorized = loginId.substring(0, 3);
if (null != password) {
MD5 md5 = new MD5();
encPassword = md5.getPassword(password);
}
if (checkLoginId == null) {
return "Incorrect loginId..Please enter valid loginId";
} else if (encPassword.equals(uPassword)) {
if (checkAuthorized.equals("STE")) {
List<CompanyMaster> companyList = userService.getCompanyList(OrgLoginId);
return companyList;
} else {
return "You are not Authorized";
}
} else {
return "Incorrect Password";
}
Yes its possible, create a custom Exception say 'MyAppException' and throw that exception with the error message you want.
Write your logic in a try{}catch block and throw the exception in catch so that the response has the error message
public List<CompanyMaster> getCompanies(#RequestBody UserDetails user) throws MyAppppException
{
try
{
//your logic which throws error
return companyList;
}
catch( final MyAppException we )
{
throw new MyAppException("User not found", HttpStatus.NOT_FOUND);
}
}
Refer this link
https://www.codejava.net/java-core/exception/how-to-create-custom-exceptions-in-java
You can achieve this by creating a new presenter Class which contains List and status of type String and change the return type of getCompanies method to presenter class like
public CompaniesPresenter getCompanies()
And your CompaniesPresenter class should look like
public class CompaniesPresenter {
private List<CompanyMaster> companyMaster;
private string status;
//default constructor
public CompaniesPresenter(){
}
//parameterized constructor to return only string in exception case
public CompaniesPresenter(Stirng status){
this.status = status;
}
//parametirized constructor to return success case
public CompaniesPresenter(List<CompanyMaster> companyMaster, Stirng status){
this.companyMaster = companyMaster;
this.status = status;
}
//getters and setters
}
This is how your updated method lokks like
#RequestMapping(value = "/getcompanies", method = RequestMethod.POST)
public CompaniesPresenter getCompanies(#RequestBody UserDetails user) {
String OrgLoginId = user.getOrgLoginId();
String password = user.getuPassword();
String checkLoginId = null;
String uPassword = null;
String encPassword = null;
String loginId = null;
String checkAuthorized = null;
// String loginId=userService.getLoginId(OrgLoginId);
List<Object[]> CheckIdPassword = userService.checkLoginId(OrgLoginId);
List<Object[]> results = CheckIdPassword;
for (Object[] obj : results) {
checkLoginId = obj[0].toString();
if (null == obj[1]) {
uPassword = "";
} else {
uPassword = obj[1].toString();
}
loginId = obj[2].toString();
}
checkAuthorized = loginId.substring(0, 3);
if (null != password) {
MD5 md5 = new MD5();
encPassword = md5.getPassword(password);
}
if (checkLoginId == null) {
return new CompaniesPresenter("Incorrect loginId..Please enter valid loginId");
} else if (encPassword.equals(uPassword)) {
if (checkAuthorized.equals("STE")) {
List<CompanyMaster> companyList = userService.getCompanyList(OrgLoginId);
return new CompaniesPresenter(companyList,"success");
} else {
return new CompaniesPresenter("You are not Authorized");
}
} else {
return new CompaniesPresenter("Incorrect Password");
}
This is not tested please make sure for any compilation errors
vavr's Either class would be a good choice.
The usage of custom exception is most reasonable solution. However, creating custom exception for just one case is not ideal always.
Another solution is to return empty List from your method, check if the List is empty in your servlet (or wherever you are invoking this method from), and show error message there.
It seems like you want to return multiple error messages for different cases. In this case, custom exception is recommended solution. If you don't like custom exceptions, you can return List<Object> and populate error message as the first element in the list. In the place where this List is obtained, check if the first element is instanceOf String or CompanyMaster. Based on what it is, you can perform your operations. This is a weird but possible solution (only if you don't like custom exceptions).
You need to understand the problem first. You are mixing two things here, first authorization, does the user has correct privileges to get company details, second giving the company details itself. Let's understand the first problem when a user tries to access "/getcompanies" endpoint will you let him in if does not have access, in REST world your security model should take care of it. I would use spring security to achieve this. My recommendation would be to explore on "interceptor" and solve the problem of invalid user. This will make your other problem easy as your "/getcompanies" endpoint can focus only on getting the details and return it (SRP).

Trying to insert the Element into ArrayList but, instead of inserting its updating with the current value

I have a below piece of code where I fetch the json data and pass it to the another method. Data will be keep changing on daily basis. Here, I want to retain my old Data, but somehow I am unable to do it.
Code to save the value:
json = getAllHistory(settings.getRapidView(),sprint.getId(),
settings.getCredentials(),settings.getBaseUrl());
List<History> historyList = new ArrayList<>();
Double completedIssues = ClientUtil.getJsonValue(json,sprint.getId(),"completedIssues");
Double allIssues = ClientUtil.getJsonValue(json,sprint.getId(),"allIssues");
Double remainingIssues = completedIssues-allIssues;
if (remainingIssues > 0) {
History history = new History();
history.setMiliseconds(ZonedDateTime.now().toInstant().toEpochMilli());
history.setCompletedIssues(completedIssues);
history.setAllIssues(allIssues);
history.setRemainingIssues(remainingIssues);
historyList.add(history);
sprintdata.gethistory().addAll(historyList);
sprintdata.setHistory(historyList);
}
Code to make the Rest call:
public static String getAllHistory(String rapidView, Long sprintId, String base64Credentials,String baseUrl) {
try
{
String query = String.format(GET_URL_DATA, rapidView, sprintId);
query=baseUrl+query;
HttpEntity<String> entity = new HttpEntity<String>(getHeader(base64Credentials));
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.exchange(query, HttpMethod.GET, entity, String.class);
String outputJson= result.getBody();
return outputJson;
}
catch (Exception e)
{
// TODO: handle exception
return null;
}
}
Code to get the specific Json value:
public static Double getJsonValue(String json, Long sprintId, String field) {
try{
return new GsonBuilder().
create().
fromJson(json, JsonObject.class).
getAsJsonObject("contents").
getAsJsonObject(field).
get("value").
getAsDouble();
}
catch(Exception ex)
{
return null;
}
}
I can't find the error on my own, so please help me.
I apologize for my mistake.
A list of one element is created.
Then to the old history list of sprintdata: all items of the new list are added (1):
sprintdata.gethistory().addAll(historyList);
Then the old sprintdata history list is replaced with the new one of 1 element:
sprintdata.setHistory(historyList);
So the sole thing to do would be: add one element to the old history list.
sprintdata.gethistory().add(history);

return any exception in json in rest api

Is there any simple methods to return exception in JSON using Rest api?
I've already googled this question, but all solutions i see, was about throwing exceptions during some calculations. But what if income parameters are wrong? I mean what if there is sone string instead of int input parameter?
I created some DTO class for input data:
#XmlRootElement
public class RequestDTO implements Serializable{
private static final long serialVersionUID = 1L;
#XmlElement(name = "request_id")
private String requestId;
#XmlElement(name = "site")
private List<String> sitesIds;
#XmlElement(name = "date_begin")
#JsonSerialize(using = DateSerializer.class)
#JsonDeserialize(using = DateDeserializer.class)
private Date dateBegin;
#XmlElement(name = "date_end")
#JsonSerialize(using = JsonDateSerializer.class)
#JsonDeserialize(using = JsonDateDeserializer.class)
private Date dateEnd;
#XmlElement(name = "volume")
private double volume;
// there is getters and setters
}
If i sent something like 'qwerty' instead of 'volume' field in my json request i'l see error message like Runtime. Is it possible to handle it in someway? I mean to return error in json with such structure?
public class ExceptionDTO {
private String shortExceptionMessage;
private String stackTrace;
public ExceptionDTO(String shotExceptionMessage, String stackTrace){
this.shortExceptionMessage = shotExceptionMessage;
this.stackTrace = stackTrace;
}
public String getShortExceptionMessage() {
return shortExceptionMessage;
}
public String getStackTrace() {
return stackTrace;
}
}
UPD1:
#Provider
#Singleton
public class ExceptionMapperProvider implements ExceptionMapper<Exception>{
#Override
public Response toResponse(final Exception e) {
StringBuilder trace = new StringBuilder();
IntStream.range(0, e.getStackTrace().length)
.forEach(i -> trace.append(e.getStackTrace()[i]).append('\n'));
ExceptionDTO exceptionMessage = new ExceptionDTO(
e.toString(),
trace.toString()
);
return Response.status(500).entity(exceptionMessage).build();
}
}
As it's not really clear if you are interested on checking if field or value of the payload is correct, here are a few ways to work with both.
If you want to check if the value for a field is correct (ie volume field value should be greater than zero etc), check out bean validation. This makes use of annotations on the fields you want to verify.
// for example
#Min(value = 0, message = "invalid message")
private double range;
To use your ExceptionDTO as error response whenever one of those validation fails, you can do so by creating an ExceptionMapper<ConstraintViolationException>. check it here for more details.
If you are checking for the invalid field (ie client sends ragne fields instead of range), have a look at the stack trace on what exception is being thrown. Then register an exception mapper with your ExceptionDTO as body.
For example, if UnrecognizedPropertyException is thrown then you can add:
#Provider
public class UnrecognizedPropertyExceptionMapper implements ExceptionMapper<UnrecognizedPropertyException> {
#Override
public Response toResponse(UnrecognizedPropertyException e) {
ExceptionDTO myDTO = // build response
return Response.status(BAD_REQUEST).entity(myDTO).build();
}
}
If you want to validate input parameters in the request, you should return status code 400 (Bad Request) along with the error details. You can simply send json
{ "error": { "message": "string received for parameter x, where as int expected" } with the response status code 400.
`
I did a bit of research and determined that the best way to encode a Java exception in JSON is to use a convention developed by Oasis that looks like this:
{
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
details is a list that should have an entry for each nested cause exception in the chain.
innererror.trace should include the stack trace if you wish, as a list of string values.
The response status code should be 400 unless you have a good reason for making it something else, and the code in the structure should match whatever you sent.
Write one method to convert a Java exception to this format, and you are done. Use it consistently and your JS code will be able to handle and display the exception values.
More of the details of the other approaches evaluated and dismissed are covered in this blog post on JSON REST API – Exception Handling
https://agiletribe.purplehillsbooks.com/2015/09/16/json-rest-api-exception-handling/
Here is the java method to convert an exception to this format:
public static JSONObject convertToJSON(Exception e, String context) throws Exception {
JSONObject responseBody = new JSONObject();
JSONObject errorTag = new JSONObject();
responseBody.put("error", errorTag);
errorTag.put("code", 400);
errorTag.put("target", context);
JSONArray detailList = new JSONArray();
errorTag.put("details", detailList);
String lastMessage = "";
Throwable runner = e;
while (runner!=null) {
String className = runner.getClass().getName();
String msg = runner.toString();
runner = runner.getCause();
JSONObject detailObj = new JSONObject();
detailObj.put("message",msg);
int dotPos = className.lastIndexOf(".");
if (dotPos>0) {
className = className.substring(dotPos+1);
}
detailObj.put("code",className);
System.out.println(" ERR: "+msg);
detailList.put(detailObj);
}
JSONObject innerError = new JSONObject();
errorTag.put("innerError", innerError);
JSONArray stackList = new JSONArray();
runner = e;
while (runner != null) {
for (StackTraceElement ste : runner.getStackTrace()) {
String line = ste.getFileName() + ":" + ste.getMethodName() + ":" + ste.getLineNumber();
stackList.put(line);
}
stackList.put("----------------");
runner = runner.getCause();
}
errorTag.put("stack", stackList);
return responseBody;
}

Jackson double serialized json string to Java object

I have a Json string which has a string message field.
String:
{ "Type" : "Text",
"Subject" : "data received",
"Message" :"{\\"language\\":\\"US\\",\\"data\\":\\"signature\\"}"
}
I want to convert it into the following structure:
Notification.java
public class Notification {
String type;
String subject;
Message message;
}
Message.java
public class Message {
String language;
String data;
}
Is there a way in which I can directly convert the string to a Java object of the above structure? I want to avoid deserializing twice.
You can create a custom Deserializer to deserialize the Message text into Message object and annotate the Message class with #JsonDeserialize:
#JsonDeserialize(using = MessageDeserializer.class)
public class Message {
String language;
String data;
}
public class MessageDeserializer extends JsonDeserializer<Message> {
public MessageDeserializer() {
super();
}
#Override
public Message deserialize(
final JsonParser jsonParser, final DeserializationContext deserializationContext) throws
IOException, JsonProcessingException {
final String messageText = jsonParser.getText();
// parse messageText into Message object
}
}
I am not sure my solution is acceptable since it does require additional explicit call to ObjectMapper to perform deserialization of the string value of Message.
However, this is it is done during the buildup of Notification object and does not require a String message property.
You need to add a ctor with String argument to Message class, where you can deserialize the String into Map and extract the instance propertieds:
public Message(String str) {
try {
#SuppressWarnings("unchecked")
Map<String, Object> map =
(Map<String, Object>)new ObjectMapper().readValue(str, Map.class);
language = map.containsKey("language") ? map.get("language").toString() : null ;
data = map.containsKey("data") ? map.get("data").toString() : null ;
} catch (Exception e) {
e.printStackTrace();
}
}
the new ctor will be called by Jackson when you deserialize a Notification object:
Notification n = (Notification)new ObjectMapper().readValue(reader, Notification.class);
You can convert json string into key-value pairs in Map.You will have to do twice as the Message value is again a json string.Use org.json for JSONObject
Map<String, String> map = new HashMap<String, String>();
JSONObject j = new JSONObject(str);
Iterator<String> keys = j.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String val = j.getString(key);
map.put(key, val);}
Then retrieve the values by iterating over the keys and pass the values into the class constructor
Then map.get(key) can be used to retrieve the values and will be passed into constructors of the classes.
The org.json library is easy to use:
//Create Json object to parse string
// str is input string
JSONObject obj = new JSONObject(str);
//Create Message
Message mess = new Message();
JSONObject obj2 = new JSONObject(obj.getString("Message"));
mess.data = obj2.getString("data");
mess.language = obj2.getString("language");
//Create Notification
Notification noti = new Notification();
noti.message = mess;
noti.subject = obj.getString("Subject");
noti.type = obj.getString("Type");

Remove duplicates from a Json String in Java?

I have a Json String with duplicate values:
String json = "{\"Sign_In_Type\":\"Action\",\"Sign_In_Type\":\"Action\"}";
that correctly throws an exception when I try to create a JSONObject:
try {
JSONObject json_obj = new JSONObject(json);
String type = json_obj.getString("Sign_In_Type");
} catch (JSONException e) {
throw new RuntimeException(e);
}
Error:
Exception in thread "main" java.lang.RuntimeException: org.json.JSONException: Duplicate key "Sign_In_Type"
at com.campanja.app.Upload.main(Upload.java:52)
Caused by: org.json.JSONException: Duplicate key "Sign_In_Type"
at org.json.JSONObject.putOnce(JSONObject.java:1076)
at org.json.JSONObject.(JSONObject.java:205)
at org.json.JSONObject.(JSONObject.java:402)
at com.campanja.app.Upload.main(Upload.java:49)
Is there a smart way of removing or checking for duplicates before I convert it to a JSONOBject?
I have tried to create:
Set set = new HashSet(Arrays.asList(json));
but that gives me:
[{"Sign_In_Type":"Action","Sign_In_Type":"Action"}]
Any suggesstions welcome, thanks!
Two options I can think of right off the bat:
Parse the string using wither regex or tokens, add each key-value pair to a hashmap, and in the end recreate your JSON document with the duplicates removed. In this case though I would only remove key-value pairs that are exactly the same.
Download the source code for org.json.JSONObject , and make a slight modification to the code to automatically leave out duplicates. This is a bit dangerous though. Another option is to create a modified version that simply validates and modifies.
Extending JSONObject Working Example
The below code allows you to create a JSONOBbject with a string containing duplicate keys. Exceptions are thrown only when you have two key-values that have the same key, but different values. This was because I think it would be a problem to choose at random which of the two should be assigned (e.g. the later value?). Of course this can be changed to work as you wish (e.g. keep last value for multiple keys).
Modified Class
import org.json.JSONException;
import org.json.JSONObject;
public class JSONObjectIgnoreDuplicates extends JSONObject {
public JSONObjectIgnoreDuplicates(String json) {
super(json);
}
public JSONObject putOnce(String key, Object value) throws JSONException {
Object storedValue;
if (key != null && value != null) {
if ((storedValue = this.opt(key)) != null ) {
if(!storedValue.equals(value)) //Only through Exception for different values with same key
throw new JSONException("Duplicate key \"" + key + "\"");
else
return this;
}
this.put(key, value);
}
return this;
}
}
Main method
String json = "{\"Sign_In_Type\":\"Action\",\"Sign_In_Type\":\"Action\"}";
try {
JSONObject json_obj = new JSONObjectIgnoreDuplicates(json);
String type = json_obj.getString("Sign_In_Type");
} catch (JSONException e) {
throw new RuntimeException(e);
}
Assuming that
String json = "{\"Sign_In_Type\":\"Action\",\"Sign_In_Type\":\"Action\"}";
is a fiction for testing, can I ask whether creating the data as a String is the best choice in the first place? Why not a HashMap, or some other structure that either overwrites the subsequent reuses of a name or ignores them or throws an error when you add them? Don't wait until the conversion to JSON to make your data valid.
You can make use of the Jackson library to parse JSON. I'd problems doing the same task as you with org.json's package, but I turned to Jackson and I solved it: http://wiki.fasterxml.com/JacksonHome
I expanded Menelaos Bakopoulos answer, so that if inner values are also with duplicates, it won't create issues. the former solution worked on the first level only.
public class JSONObjectIgnoreDuplicates extends JSONObject {
public JSONObjectIgnoreDuplicates(JSONTokener x) throws JSONException {
super(x);
}
#Override
public JSONObject putOnce(String key, Object value) throws JSONException {
Object storedValue;
if (key != null && value != null) {
if ((storedValue = this.opt(key)) != null) {
if (!storedValue.toString().equals(value.toString())) //Only throw Exception for different values with same key
throw new JSONException("Duplicate key \"" + key + "\"");
else
return this;
}
this.put(key, value);
}
return this;
}
}
private class JsonDupTokener extends JSONTokener {
public JsonDupTokener(String s) {
super(s);
}
#Override
public Object nextValue() throws JSONException {
char c = this.nextClean();
switch (c) {
case '\"':
case '\'':
return this.nextString(c);
case '[':
this.back();
return new JSONArray(this);
case '{':
this.back();
return new JSONObjectIgnoreDuplicates(this);
default:
StringBuffer sb;
for (sb = new StringBuffer(); c >= 32 && ",:]}/\\\"[{;=#".indexOf(c) < 0; c = this.next()) {
sb.append(c);
}
this.back();
String string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
} else {
return JSONObject.stringToValue(string);
}
}
}
}
Sorry I can't comment on Menelaos Bakopoulos' response due to reputation<50... Stupid system
Your solution unfortunately does not work here:
SEVERE: ERROR converting JSON to XML org.json.JSONException: Duplicate key "id"
org.json.JSONObject.putOnce(JSONObject.java:1076)
org.json.JSONObject.<init>(JSONObject.java:205)
org.json.JSONTokener.nextValue(JSONTokener.java:344)
org.json.JSONArray.<init>(JSONArray.java:125)
org.json.JSONTokener.nextValue(JSONTokener.java:348)
org.json.JSONObject.<init>(JSONObject.java:205)
JSONUtilities.JSONObjectIgnoreDuplicates.<init>(JSONUtilities.java:38)
It seems that calling super(json) in JSONObjectIgnoreDuplicates's constructor sends the code into a loop inside JSONObject, not JSONObjectIgnoreDuplicates ;{
I'm currently trying Asaf Bartov's solution, but there's no call from JSONObjectIgnoreDuplicates to JsonDupTokener, so appart from overloading the constructor of JSONObjectIgnoreDuplicates as follows, I don't see how it could work:
public JSONObjectIgnoreDuplicates(String json) throws JSONException {
this(new JSONDupTokener(json));
}
EDIT: I can confirm this works :))))
Thanks everybody!!!!
With Google Gson you can decide what to do with duplicates in the input string. You need to register your own TypeAdapter responsible for serialization/deserialization of objects. It would look like this:
// this implementation converts the json string to a Map<String, String>,
// saving only the first duplicate key and dropping the rest
class NoDuplicatesAdapter extends TypeAdapter<HashMap<String, String>> {
#Override
public void write(JsonWriter out, HashMap<String, String> value) throws IOException {
out.beginObject();
for (Map.Entry<String, String> e: value.entrySet()) {
out.name(e.getKey()).value(e.getValue());
}
out.endObject();
}
#Override
public HashMap<String, String> read(JsonReader in) throws IOException {
final HashMap<String, String> map = new HashMap<>();
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
// putting value to the map only if this key is not present;
// here you can actually find duplicate keys and decide what to do with them
map.putIfAbsent(name, in.nextString());
}
in.endObject();
return map;
}
}
Then you can parse your string:
String json = "{\"Sign_In_Type\":\"Action\",\"Sign_In_Type\":\"Action\"}";
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> map = new GsonBuilder()
.registerTypeAdapter(mapType, new NoDuplicatesAdapter())
.create()
.fromJson(str, mapType);
The map will contain only the first "Sign_In_Type".

Categories