POST feeds/_doc
{
"feed_id": "3",
"title": "jose ",
"body": "This is Jose allen",
"comment": [
{
"c_id": "13",
"feed_id": "2",
"c_text": "hey"
},
{
"c_id": "13",
"feed_id": "3",
"c_text": " here"
}
]
}
this is the mapping
PUT feeds
{
"mappings": {
"properties": {
"comment":{
"type": "nested"
}
}
}
}
I want to create feed class with mentioned feilds the comment field has nested type fields with sub fileds of c_text,c_id .how can i create it
#Document(indexName = "feeds")
public class Feed {
#Id
private String feed_id;
#Field(type = FieldType.Text, name = "title")
private String title;
#Field(type = FieldType.Text, name = "body")
private String body;
#Field(type= FieldType.Nested , name="comment")
private String[] comment;
}
how to intialize subfields of comment field as i am using elasticsearch 7.17.3
You can create a Comment class like this:
public class Comment {
#JsonProperty("c_id")
private String cId;
#JsonProperty("feed_id")
private String feedId;
#JsonProperty("c_text")
private String cText;
// Getters, setters, ...
}
and instead of using private String[] comment, you should use:
#Field(type= FieldType.Nested , name="comment")
private List<Comment> comment;
Related
I want to parse the json string and form a pojo object but the response is somewhat unusual.
I have folloing type of response from API
"data": {
"12": {
"value": "$0.00",
"order_id": "12",
"order_date": "2020-08-26 15:50:05",
"category_name": "Games",
"brand_id": "4",
"denomination_name": "AED 50",
"order_quantity": "1",
"vendor_order_id": "A-123",
"vendor_location": "",
"vouchers": {
"804873": {
"pin_code": "41110AE",
"serial_number": "fddfgfgf1234444"
}
}
},
"15": {
"value": "$0.00",
"order_id": "15",
"order_date": "2020-08-26 08:39:11",
"category_name": "Games",
"brand_id": "52",
"brand_name": "PlayStation",
"denomination_name": "$20",
"order_quantity": "1",
"vendor_order_id": "A-316",
"vendor_location": "",
"vouchers": {
"806328": {
"pin_code": "fdfd",
"serial_number": "fawwwww"
}
}
}
}
}
How do I parse this response since inside data the field name is order id same with voucher
If you use Jackson JSON library, you should have POJOs like those shown below and use PropertyNamingStrategy.SnakeCaseStrategy to handle property names in the input JSON:
// top-level container
public class Response {
private Map<Integer, Order> data;
// getter/setter
}
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Order {
private String value; // may be some Currency class
private Integer orderId;
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime orderDate;
private String categoryName;
private Integer brandId;
private String brandName;
private String denominationName; // may be Currency too
private Integer orderQuantity;
private String vendorOrderId;
private String vendorLocation;
private Map<Integer, Voucher> vouchers;
// getters/setters
}
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Voucher {
private String pinCode;
private String serialNumber;
// getters/setters
}
I am writing an annotation processor and i need to scan all classes with certain annotation to get all fields and create json object with same structure of the class.
For example:
#ClassToJson
public class Person {
private String name;
private String surname;
/*getter and setter*/
}
My output is:
{
"name": "string",
"surname": "string"
}
Now i am wondering how can i handle classes like this one:
public class PhoneNumber {
private String countryCode;
private String phoneNumber;
/*getter and setter*/
}
#ClassToJson
public class Person {
private String name;
private String surname;
private PhoneNumber phoneNumber;
/*getter and setter*/
}
i would like get output like this:
{
"name": "string",
"surname": "string",
"phoneNumber": {
"countryCode": "string",
"phoneNumber": "string"
}
}
I'm using retrofit at my android application. At my webapi, there is a nested json result which i need to parse. Not nested ones are fine, but when i encountered nested one, it seems i can't parse them.
This is my json example. I've shortened it a bit but all same.
When i executed call method, it just bypassing onResponse or onFailure.
I'm thinking i made a mistake at my class file but i cant figure out what or how.
JSON:
[
{
"name": "All joined for mobile",
"selectedOnes": [
"1",
"2"
],
"lines": [
{
"details": "",
"cancelDetails": null,
"isCancel": null,
"hours": [
{
"arrivalTime": "",
"departTime": "07:15:00"
},
{
"arrivalTime": "07:30:00",
"departTime": ""
}
]
},
{
"details": "",
"cancelDetails": null,
"isCancel": null,
"hours": [
{
"arrivalTime": "",
"departTime": "07:30:00"
},
{
"arrivalTime": "07:45:00",
"departTime": ""
}
]
}
]
}
]
ParsedJsonClass.java:
public class ParsedJsonClass {
#SerializedName("name")
#Expose
private String name;
#SerializedName("selectedOnes")
#Expose
private List<String> selectedOnes = null;
#SerializedName("lines")
#Expose
private List<lines> lines = null;
public class lines {
#SerializedName("details")
#Expose
private String details;
#SerializedName("cancelDetails")
#Expose
private Object cancelDetails;
#SerializedName("isCancel")
#Expose
private Object isCancel;
#SerializedName("hours")
#Expose
private List<hours> hours = null;
public class hours {
#SerializedName("arrivalTime")
#Expose
private String arrivalTime;
#SerializedName("departTime")
#Expose
private String departTime;
}
}
}
So, we're working in java, the object being deserialized is structured as so
#ApiModel(description = "Container for collection of Patient Search results")
public class PatientSearchResultListCMRefactor {
private final List<PatientSearchResultCMRefactor> patientSearchResults;
private final int totalSearchResults;
//getters, toString, etc
}
The object referenced in that object is as follows
public final class PatientSearchResultCMRefactor {
private float score;
private String id;
private String firstName;
private String lastName;
private String setupDate;
private Optional<AddressCM> address;
private Optional<Boolean> active;
private Optional<String> dateOfBirth;
private Optional<String> email;
private Optional<String> patientExternalId;
private Optional<String> patientReference;
private Optional<String> phoneNumber;
private Optional<String> currentAverageDaysUsed;
private Optional<Double> currentAverageHoursUsed;
private Optional<PatientOrganizationCM> organization;
private Optional<PatientOrganizationCM> topOrganization;
private Optional<ImmutableSet<PatientClinicianCM>> clinicians;
private Optional<ImmutableSet<PatientLocationCMRefactor>> locations;
private Optional<ImmutableSet<PatientDeviceCM>> devices;
private Optional<String> matchesBy;
//setters, getters, left-handed smoke-shifters, constructors
}
the code to deserialize it is
Gson gson = new Gson();
System.out.println(response.getBody());
String jsonTemp = response.getBody();
System.out.println(jsonTemp);
PatientSearchResultListCMRefactor resultListCM = gson.fromJson(jsonTemp, PatientSearchResultListCMRefactor.class);
The full string being deserialized is
{
"patientSearchResults": [
{
"score": 0.7582117,
"id": "3910dc3d-913b-4862-aee5-4610d2c2981f",
"firstName": "Nelda",
"lastName": "Dixon 36",
"setupDate": "2018-07-19",
"address": {
"streetAddress": "0545 Route 202",
"city": "Joliet",
"stateProvince": "SC",
"zipCode": "87636",
"countryCode": "USA"
},
"active": true,
"dateOfBirth": "1971-01-16",
"email": "n_dixon_RRAwyqXKIp#example.com",
"patientExternalId": "6bc63dfa-1106-40c9-875a-a74368cf5189",
"patientReference": null,
"phoneNumber": "365-177-2753",
"currentAverageDaysUsed": null,
"currentAverageHoursUsed": null,
"organization": null,
"topOrganization": null,
"clinicians": [
],
"locations": null,
"devices": [
],
"matchesBy": null
}
],
"totalSearchResults": 17
}
The error is
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BOOLEAN at line 1 column 289
which is right after
"address": {
"streetAddress": "0545 Route 202",
"city": "Joliet",
"stateProvince": "SC",
"zipCode": "87636",
"countryCode": "USA"
},
"active": true,
in the string, with the comma after "true" being column 289 (for clarification, line and column numbers are from before I prettyprinted the string). I think it's expecting a new object, but address is a sub-object nested in the top object, and sub-objects never go more than 1 level deep, though per the PatientSearchResultCMRefactor model there are multiple sub-objects. I'm a tester, and this is the body of a ReST API call, so I can't really change the format of the response. All I can do is try to parse it as-is. Any tips?
UPDATE: It turns out, gson has real trouble with optional variables and immutable sets. Once I changed PatientResultCMRefactor to
public final class PatientSearchResultCMRefactor {
private float score;
private String id;
private String firstName;
private String lastName;
private String setupDate;
private AddressCM address;
private Boolean active;
private String dateOfBirth;
private String email;
private String patientExternalId;
private String patientReference;
private String phoneNumber;
private String currentAverageDaysUsed;
private Double currentAverageHoursUsed;
private PatientOrganizationCM organization;
private PatientOrganizationCM topOrganization;
private Set<PatientClinicianCM> clinicians;
private Set<PatientLocationCMRefactor> locations;
private Set<PatientDeviceCM> devices;
private String matchesBy;
//getters, setters, etceterrers
}
Everything deserializes perfectly. Posting this as an answer rather than updating the question to make it easier for others to find in the future.
I have a Json list using object with children
{
"id":"154",
"name":"peter",
"children": [
{
"id":"122",
"name": "mick",
"children":[]
},
{
"id":"123",
"name": "mick",
"children":[]
}
]
}
Here is the class of my object:
public class person{
private String id;
private String name;
private List<person> children;
//getters and setters
}
When I try to deserialize this object, I have the following error
Can not deserialize instance of person out of START_ARRAY token
What should I do ?
The JSON contains an array of persons.
Your class a List of person.
Either change the JSON like #Naveed Yadav suggested or change the class to
public class Person{
private String id;
private String name;
private Person[] children;
//getters and setters
}
(BTW the class name should be upper case in Java)
Fix syntax errors in your JSON body and you'll be in a good shape:
{
"id":"154",
"name":"peter",
"children": [
{
"id":"122",
"name": "mick",
"children":[], <== Excess comma
} <== Missing comma
{
"id":"123",
"name": "mick",
"children":[], <== Excess comma
}
]
}
Valid one:
{
"id": "154",
"name": "peter",
"children": [{
"id": "122",
"name": "mick",
"children": []
},
{
"id": "123",
"name": "mick",
"children": []
}
]
}
You need to change your POJO declaration like below:-
public class person{
private String id;
private String name;
private List<Children> children;
//getters and setters
private class Children{
private String id;
private String name;
private String[] children;
}
{
"id":"154",
"name":"peter",
"children":
{
"id":"122",
"name": "mick",
"children":[],
}
{
"id":"123",
"name": "mick",
"children":[],
}
}