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())
Related
I want to make a string from json into an object of my class. The problem is, in the class I use an ArrayList and that's why (I think) I get the error message "Can't deserialize JSON array into class". How exactly can I separate the array and convert it into an ArrayList?
#POST
public Response createMocktail(String m){
MocktailDto mocktail = jsonb.fromJson(m, MocktailDto.class);
return Response.ok(mocktailManager.createMocktail(mocktail)).build();
}
Json String:
[
{
"id": 3,
"name": "Mojito",
"zutaten": [
{
"anzahl": 1,
"id": 5,
"name": "Rum"
},
{
"anzahl": 1,
"id": 6,
"name": "GingerAle"
}
]
}
]
JSONObject jsonObj = new JSONObject(m); does not work, it says constructor is undefined although I saw a few solutions like this
The problem is your input string is Array (when it starts with [)
There are a few possible solutions:
First:
MocktailDto[] data = jsonb.fromJson(m, MocktailDto[].class);
data[0];
Second:
Type listType = new TypeToken<ArrayList<MocktailDto>>(){}.getType();
ArrayList<MocktailDto> data = jsonb.fromJson(m, listType);
data.get(0);
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.
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);
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
{
"Header": {
"AppId": "appiddfdsf324",
"RecId": "fdsfrecid79878_879898_8797",
"SecureRefId": "fsdf5679567fsd_6789678",
"Type": "Other",
"Ver": "9.0.0",
"StartTS": "2016-09-26:07:48.798798-04:00"
},
"Application": {
"APP_OS": "Windows",
"APP_Runtime": ".Net67986",
"APP_AppName": "MPS",
"APP_AppVersion": "9.0.0.0",
"Host": "fsdhajkfh657895fsdajf",
"Channel": "N/A",
"APP_ReqId": "2f3d7987987-78987-987987-897-da"
},
"Service": {
"Key": "modification process",
"CallType": "HGDL",
"Operation": "processrequest",
"Port": "n/a"
},
"Results": {
"Elapsed": 0,
"Message": "Message Succesfully Deleted",
"TraceLevel": "Information"
},
"Security": {
"Vendor": "abfsdf"
},
"Extended_Fields": {
"CustomerId": "4564987987",
"MessageId": "768789fsdafasdf987987987fasdf",
"TimeElapsed": "1272.8171"
}
}
in above string value we are capturing from website result values we will get in a string format by using selenium webdriver.
This i need to convert and read value of "Message"
Note : i have tried below code
JsonElement jelement = new JsonParser().parse((String) elementText);
JsonObject jobject = jelement.getAsJsonObject();
jobject.getAsJsonObject("Results");
This above will provide complete result value of Result json but i required to fetch values which is present with "Message"
Below first line creates the JSONObject by passing String [which is of JSON format and it should be in JSON format, otherwise it will through an exception]
In Second line , as you have a JSON Object now, you can fetch any element from that,
e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type,
we can access any element by using . and depending on what are you fetching use get
e.g getString -> for getting String,
getInt->for getting Integer,
JSONObject-> for getting an JSONObject
getJSONArray-> for getting a JSONArray
JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object
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.