Hey i got an issue based on deserialization with jackson, here what i've tried and the error i got.
ERROR : com.fasterxml.jackson.core.JsonParseException: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
Java Code
List<Contact> ds = mapper.readValue(data, mapper.getTypeFactory().constructCollectionType(List.class, Contact.class));
//OR this one
List<Contact> ds = mapper.readValue(data, new TypeReference<List<Contact>>() {});
My JSON
[
{
"id": "200",
"name": "Alexia Milano",
"email": "minalo#gmail.com",
"prenom": "xx-xx-xxxx,x - street, x - country",
}, {
"id": "201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"prenom": "xx-xx-xxxx,x - street, x - country",
}
]
If you use json validator, you can see more detailed error message:
Parse error on line 6:
...ntry", }, { "id
---------------------^
Expecting 'STRING'
you have extra comma there after "xx-xx-xxxx,x - street, x - country". If you remove it from both two places, you have valid JSON and Jackson parsing works.
It's because your last entries, there is an , after your last value. Thats why jackson expects another field.
Related
I have a json array to work with, like so:
[
{
"id": "12345",
"eauthId": "123451234512345123451234512345",
"firstName": "Jane",
"middieInitial": "M",
"lastName": "Doe",
"email": "janedoe#usda.gov",
"roles": [
{
"id": "CTIS_ROLE_ID",
"name": "A test role for CTIS",
"treatmentName": "Fumigation"
}
]
},
{
"id": "67890",
"eauthId": "678906789067890678906789067890",
"firstName": "John",
"middieInitial": "Q",
"lastName": "Admin",
"email": "johnadmin#usda.gov",
"roles": [
{
"id": "CTIS_ADMIN",
"name": "An admin role for CTIS",
"treatmentName": "System Administration"
}
]
}
]
My task is to find out the user's "roles" --> "name", once match, get that user's email address and sign in using that email address. It seems like a simple task, but it has been really kicking my bottom, since digging into API is new to me. I've tried different libraries (Jackson, RestAssured, Json Simple) and finally GSon. I don't have time to sit and study everything from the scratch. I just needed a quick solution. But it definitely hasn't been quick. Is anyone kind enough to help me out with this. I'd really appreciate it.
closeableHttpResponse = restClient.get(ConfigurationReader.get("base_url") + ConfigurationReader.get("user_endpoint"));
//Status code
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println("statusCode = " + statusCode);
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Type userListType = new TypeToken<List<Users>>(){}.getType();
List<Users> users = (List<Users>) new Gson().fromJson(responseString, userListType);
Roles roles = new Gson().fromJson(responseString, Roles.class);
it gives me this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:932)
The problem with your code is
Type userListType = new TypeToken<List>(){}.getType();
List users = (List) new Gson().fromJson(responseString, userListType);
You are not receiving just a list, you are actually deserializing an array of lists.
So try this:
List[] users = (List[]) new Gson().fromJson(responseString, List[].class);
I was hoping to use Jackson to find JSON diff but it does not give detailed error messages.
So I tried using JSOnAssert to find the diff between two JSON strings.
JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, false);
Sadly, it does not appear to match correctly and give the detailed error messages as in the examples. If you have used it, Can you please clarify?
java.lang.AssertionError: data[0] Could not find match for element {"errors":[{"httpStatus":"BAD_REQUEST","personId":null,"details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}],"successfulIds":["A0","B1","C3"]}
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:222)
Actual JSON:
{"_links":{"self":{"href":"https://myserver.com:1000/api/person/upload? myCsvFile={myCsvFile}","templated":true}},"data":[{"successfulIds":["A0","XYZ","C3"],"errors":[{"personId":null,"httpStatus":"BAD_REQUEST","details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}]}]}
Expected JSON:
{
"_links": {
"self": {
"href": "https://myserver.com:1000/api/person/upload?myCsvFile={myCsvFile}",
"templated": true
}
},
"data": [
{
"successfulIds": [
"A0",
"B1",
"C3"
],
"errors": [
{
"personId": null,
"httpStatus": "BAD_REQUEST",
"details": "User ID [UNKNOWN]. Invalid ID: NONSENSE"
}
]
}
]
}
I tried to email the address at http://jsonassert.skyscreamer.org/ but got a
The following message to jsonassert-dev#skyscreamer.org was
undeliverable. The reason for the problem:
5.1.0 - Unknown address error 550-"5.1.1 The email account that you tried to reach does not exist
So I tried ZJsonPatch. I like the fact that using Jackson with it, the ordering of the members does not matter. In other words, I first try to check for equality using Jackson. Jackson is ordering independent. Then if it fails, I use ZJsonPatch to tell me what the diff is.
{"op":"replace","path":"/data/0/successfulIds/1","value":"B9"}
which handles nested JSON well.
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(expectedJsonResponse);
JsonNode actual = mapper.readTree(actualJsonResponse);
try {
assertEquals(expected, actual);
} catch (AssertionError ae) {
JsonNode patch = JsonDiff.asJson(actual, expected);
throw new Exception(patch.toString(), ae);
}
I'm getting my JSON values from a linkedHashMap
LinkedHashMap<String,Object> lst = JsonPath.parse(json).read("$.projects[0].issuetypes[0].fields");
This is the JSON I'm trying to parse :
{
"required": false,
"schema": {
"type": "string",
"custom": "com.atlassian.jira.plugin.system.customfieldtypes:textfield",
"customId": 10161
},
"name": "Error Code",
"operations": [
"set"
]
}
Then I was thinking that this would do the job
JSONObject jsonObject = new JSONObject(lst.get(key).toString());
But then I got this exception:
Exception in thread "main" org.codehaus.jettison.json.JSONException: Expected a ',' or '}' at character 95 of {required=false, schema={type=string, custom=com.atlassian.jira.plugin.system.customfieldtypes:textfield, customId=10161}, name=Error Code, operations=["set"]}
Character 95 is the colon between customfieldtypes and textfield
What could be wrong with this ?
You are trying to parse a serialized object, which is not valid JSON.
lst.get(key).toString()
does not produce JSON.
I have defined a class Email having following details:
Email:
String name;
String subject;
List<String> attachment;
String jsonContent;
....
In above class, jsonContent variable is loaded with a strinigified json object.
Once an Email object is created, I am stringifying the whole Email object and sending to client.
I need to parse Email object in client and render it in UI.
But it throws parsing error for Email object in client, i.e.
JSON.parse(emailString);
because jsonContent field is having double quotes within it.
It is a problem of stringifying a JAVA object having a jsonContent variable which is already stringified.
One way to fix it is define jsonContent variable as a object rather than as a String.
Is there any other fix for it?
Example Email JSON:
{
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}"
}
You will need to escape a lot of strings to get stuff as strings.
to store a json object in a json object you need to escape it.
so
"jsonContent": "{
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}"
becomes
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
Now if you want to compile it in java, this is how it should look like if you would type it manually as an Java string(execute snippet)
var json = {
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
}
console.log("This is the json object having a string with json");
console.log(json);
console.log("This is it parsed as string");
var x = {hello:JSON.stringify(json)};
console.log(JSON.stringify(x).substring(10,JSON.stringify(x).length-2));
document.getElementById('content').textContent = JSON.stringify(x).substring(10,JSON.stringify(x).length-2);
<div id="content"></div>
And this is how it would look like in a JSON file/request answer thats sent
{
"id": "e4682ec0-a7c3-4f4d-abcd-f404f5fdb1eb",
"entityType": "email",
"subject": "Presentation 1",
"from": "aaa <a#a.com>",
"to": [
"undisclosed-recipients:;"
],
"cc": [],
"bcc": [
"jack.porter#forwardaccelerator.com"
],
"recievedDate": 1423101398000,
"recievedDateString": "Wed, 4 Feb 2015 12:26:38 -0800",
"bodyText": " Please find the link to my recent presentation",
"jsonContent": "{\"typeOfMail\": \"NormalMail\",\"normalMail\":{\"mailType\":\"NormalMail\",\"paragraphs\":[\"Pleasefindthelinktomyrecentpresentation\"]}}"
}
Now I don't see why you want jsonContent as a string, as you could just pass it as an object(remove the quotes surrounding it so you get
"jsonContent": {
"typeOfMail": "NormalMail",
"normalMail": {
"mailType": "NormalMail",
"paragraphs": [
"Pleasefindthelinktomyrecentpresentation"
]
}
}
and if you need it as string in javascript you can just do JSON.stringify(json.jsonContent); to get the same result easier.
I've got the following JSON feed:
{
collection_name: "My First Collection",
username: "Alias",
collection: {
1: {
photo_id: 1,
owner: "Some Owner",
title: "Lightening McQueen",
url: "http://hesp.suroot.com/elliot/muzei/public/images/randomhash1.jpg"
},
2: {
photo_id: 2,
owner: "Awesome Painter",
title: "Orange Plane",
url: "http://hesp.suroot.com/elliot/muzei/public/images/randomhash2.jpg"
}
}
}
What I am trying to do is get the contents of the collection - photo_id, owner, title and URL. I have the following code, however I am getting GSON JSON errors:
#GET("/elliot/muzei/public/collection/{collection}")
PhotosResponse getPhotos(#Path("collection") String collectionID);
static class PhotosResponse {
List<Photo> collection;
}
static class Photo {
int photo_id;
String title;
String owner;
String url;
}
}
I thought my code was correct to get the JSON feed, however I'm not so sure. Any help appreciated.
The error I get is:
Caused by: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 75
However I'm struggling to understand how to use the GSON library
Your JSON is not valid.
GSON is waiting for a BEGIN_ARRAY "[" after collection: because your PhotosResponse class define an array of Photo List<Photo> but found a BEGIN_OBJECT "{", it should be
{
"collection_name": "My First Collection",
"username": "Alias",
"collection": [
{
"photo_id": 1,
"owner": "Some Owner",
"title": "Lightening McQueen",
"url": "http://hesp.suroot.com/elliot/muzei/public/images/randomhash1.jpg"
},
{
"photo_id": 2,
"owner": "Awesome Painter",
"title": "Orange Plane",
"url": "http://hesp.suroot.com/elliot/muzei/public/images/randomhash2.jpg"
}
]
}
maybe you get that JSON from an incorrect json_encode() PHP array with key, you should encode JSON from PHP without keys, with the array values only (PHP Array to JSON Array using json_encode())