I am using Jersey client to access rest service.
I am using JSONObject and setting a "null" literal in it. It fails while it is serialized.
Upon investigating, I found JSONNull.equals() method has this "null".equals(value) then it considers the value as JSONNull object.
And then, JSONNull#isEmpty() throws exceptions.
net.sf.json.JSONObject params = new net.sf.json.JSONObject();
params.put("PGHIDENTIFIE", "null");
And when serialized it throws:
Caused by: com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject["PGHIDENTIFIE"]->net.sf.json.JSONNull["empty"])
How can I serialize that "null" value inside JSONObject? Thanks!
DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
defaultClientConfig.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(defaultClientConfig);
WebResource webResource = client.resource(apiUrl);
ClientResponse response =
webResource.path(apiUrl).accept("application/json")
.type("application/json").post(ClientResponse.class, params);
Related
Keycloak 11.0.
I am trying to create a new user in Keycloak via admin REST endpoint of Keycloak server.
I am facing stack trace on Keycloak server as below.
0 8:59:40,744 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-4) Uncaught server error: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<org.keycloak.representations.idm.CredentialRepresentation>` out of VALUE_STRING token
at [Source: (io.undertow.servlet.spec.ServletInputStreamImpl); line: 1, column: 141] (through reference chain: org.keycloak.representations.idm.UserRepresentation["credentials"])
My code is as below.
private void sendCreateUserRequest(UserEntity userEntity, KeycloakTokenModel keycloakTokenModel) throws JsonProcessingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(keycloakTokenModel.getAccessToken());
JsonObject properties = new JsonObject();
properties.addProperty(FIRST_NAME, userEntity.getFirstName());
properties.addProperty(LAST_NAME, userEntity.getLastName());
properties.addProperty(EMAIL, userEntity.getEmail());
properties.addProperty(ENABLED, DEFAULT_ENABLED_OPTION);
properties.addProperty(USERNAME, userEntity.getEmail());
String credentialsArray = mapToCredentialsArray(userEntity.getPassword());
properties.addProperty(CREDENTIALS, credentialsArray);
String propertiesString = properties.toString();
HttpEntity<String> request = new HttpEntity<>(propertiesString, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(userEndpoint, request, String.class);
}
In debugger I see
propertiesString =
{
"firstName":null,
"lastName":null,
"email":"Tester_Testerov#some.com",
"enabled":"true",
"username":"Tester_Testerov#some.com",
"credentials":
"[
{\"value\":\"verystrongpassword4\",\"type\":\"password\",\"temporary\":false}
]"
}
But without that line String credentialsArray = mapToCredentialsArray(userEntity.getPassword()); it works but I want to set credential to user in this request. Please, help
It is just bad formatted json. See that your array starts and ends with " and this is invalid syntax for json arrays. I think properties.addProperty(CREDENTIALS, credentialsArray); escapes your array with " character.
I am getting json data from an api. The api is working well when passing it through browser or postman, but there is a null response. As json is quite complicated I stringify it. My code is below:
String uri="api url";
RestTemplate restTemplate1 = new RestTemplate();
String result = restTemplate1.getForObject(uri, String.class);
System.out.println(result);//result is null
String jsonFormattedString = result.replaceAll("\\\\", "");//this throws null pointer exception
I have a special kind of parsing JSON url :
[{"exchangeRates":[{"currencyISO":"AUD","currencyShortName":"dolar"}]}]
to do that i need to pass by a proxy and a jersey client :
URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
Client client = new Client(ch);
WebResource resource = client.resource("https://api.xxxx");
resource.type(MediaType.APPLICATION_JSON);
ExchangeRates[] responseMsg = resource.path("/openapi/xxxx").get(ExchangeRates[].class);
the response is :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.xxx.ExchangeRates out of START_ARRAY token at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#236cfcf; line: 1, column: 1]
ExchangeRates is a list of ExchangeRate object.
I can't find a way how to parse this json.Any recommandation ?
I am fetching a JSONObject "result" from the following JSONObject:
{
"success" : true,
"message" : "",
"result" : {
"uuid" : "e606d53c-8d70-11e3-94b5-425861b86ab6"
}
}
I am using this code:
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "some url";
HttpGet httpget20 = new HttpGet(url);
httpget20.setHeader("apisign",buildHmacSignature(url, apisecret));
try ( CloseableHttpResponse response2 = httpclient.execute(httpget20)){
HttpEntity entity = response2.getEntity();
JSONObject obj2 = new JSONObject(EntityUtils.toString(entity));
JSONObject result = obj2.getJSONObject("result");
obj2 is the whole json object including "success", "message" and "result".
However, this line of code generates the following error message:
Exception in thread "AWT-EventQueue-0" org.json.JSONException: JSONObject["result"] is not a JSONObject.
I am not sure how a JSONObject can not be a JSONObject. Can someone explain the problem here?
JSONObject.getJSONObject can return a JSONObject only. It will not return boolean, long or String, and it will not return JSONObject.NULL in particular, because that is not a JSONObject itself (it says Java Object in the docs, and has a specific private type in the implementation).
Use isNull for checking it beforehand or just accept that it throws an exception and prepare for it. Of course you can also use the generic get and check the result against JSONObject.NULL afterwards, perhaps use instanceof, just none of these will make the code simpler and all of them will introduce casting/casting attempts at some point.
I was linking the Android docs for readability, but you can of course dig into source code too, like getJSONObject. You can find the NULL at the beginning of the same file if you are interested.
I am hitting a wall trying to get data loaded in a JSON array successfully passed to a java class that runs over the Neo4j server. My intent is to pass a list of entries from the client side to the server - nothing special here. What I am doing is reading the entries on the client side, loading those entries into JSON objects and then putting each JSON object into a JSON array which is then to be passed to the server for further processing.
Here is a section of the client side code that loads the json object and array. NOTE: the below is
just the json related code stripped down w/o the try/catch and other items resident in the code.
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value1);
jsonObject.put("field2", field2Value1);
jsonObject.put("field3", field3Value1);
jsonArray.put(jsonObject);
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value2);
jsonObject.put("field2", field2Value2);
jsonObject.put("field3", field3Value2);
jsonArray.put(jsonObject);
Here is the client side code that handles the http post part of the equation - I believe this is ok.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentType("application/json");
HttpPost post = new HttpPost(
"http://"server":7474/db/data/ext/serverSideClass/graphdb/processJSONData");
post.setEntity(stringEntity);
HTTPPostResponseResults httpResponse = new HTTPPostResponseResults();
httpResponse.checkResponse(post);
Here is the method interface to the server side code and this is where I believe my problem lies. I am thinking the parameter type needs to something other than JSONArray but am not sure what.
#Name("processJSONData")
#Description("process the data passed in.")
#PluginTarget(GraphDatabaseService.class)
public String processJSONData(#Source GraphDatabaseService graphDb,
#Parameter(name = "jsonArray") JSONArray jsonArray) {
And... here is the error being thrown.
"message" : "java.util.ArrayList cannot be cast to java.util.Map",
"exception" : "BadInputException",
"fullname" : "org.neo4j.server.rest.repr.BadInputException",
"stacktrace" : [ "org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:92)",
"org.neo4j.server.rest.repr.RepresentationFormat.readParameterList(RepresentationFormat.java:97)",
"org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension
The above should cover it for the items related to this posting. If there is anything needed to clarify this please let me know and I'll provide it. Thank you in advance.