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 ?
Related
I have a response coming from API in the following format
{"schema":[output_item, score],
"data":[[item1, 1], [item2, 2]]}
I am trying to serialize and deserialize this json using
Class1 obj = getFromApiCall();
ObjectMapper o = new ObjectMapper();
map.put("first", o.writeAsString(obj)); // Map can only accept strings
String res = map.get("first");
Object obj2 = o.readValue(res, Class1)
This is the error I am getting:
Unexpected character ('o' (code 111)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: java.io.StringReader#68bba850; line: 1, column: 13]
How do I make sure that I can serialize and deserialize the objet coming from API call?
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 below exception while parsing-
JsonMappingException org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: [B#3f5fb6a4; line: 1, column: 1]
I found several questions with same exception issue but couldn't solve my problem.
You are trying to parse a JSON object as a list. Try changing
List<Social> topics = objectMapper.readValue(response.data, objectMapper.getTypeFactory().constructCollectionType(List.class, Social.class));
into something like:
Social topics = objectMapper.readValue(response.data, Social.class);
Use this
JSONObject jsonObject = new JSONObject(response.data);
JSONArray jsonArray = jsonObject.getJSONArray("newUsers");
List<UserObject > userObject = new ObjectMapper().readValue(jsonArray.toString() , new TypeReference<List<UserObject>>(){});
for JSONObject use java-json.jar
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);
I'm using Restlet to consume a json webservice and I'm getting this error:
A JSONObject text must begin with '{' at character 1
The json response I'm getting begins with a [, which seems to be causing the issue.
Is there a way to work around this?
Here is my code:
ClientResource resource = new ClientResource(
"https://api.prosper.com/api/Listings?$top=3");
resource.setChallengeResponse(
ChallengeScheme.HTTP_BASIC, "username", "password");
Representation representation = resource.get();
JsonRepresentation jsonRepresentation = new JsonRepresentation(representation);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
Json that starts with a [ is a json array. Json that starts with { is a json object.
Use JsonRepresentation#getJsonArray()
JSONArray jsonArray = jsonRepresentation.getJsonArray();
Before you continue, familiarize yourself with the json format.