I need to include the top node in my JSON response. My JSON response in REST web service:
[
{
"address": "delhi",
"fristname": "xxxx",
"id": 1,
"lastname": "xxxx",
"phone": "0000000"
},
{
"address": "ssss",
"fristname": "yyyy",
"id": 2,
"lastname": "yyyyy",
"phone": "0000000"
},
{
"address": "wwww",
"fristname": "aaaa",
"id": 3,
"lastname": "aaaaa",
"phone": "0000000"
}
]
I want JSON response like this:
"employee": [
{
"address": "delhi",
"fristname": "xxxx",
"id": 1,
"lastname": "xxxx",
"phone": "0000000"
},
{
"address": "ssss",
"fristname": "yyyy",
"id": 2,
"lastname": "yyyyy",
"phone": "0000000"
},
{
"address": "wwww",
"fristname": "aaaa",
"id": 3,
"lastname": "aaaaa",
"phone": "0000000"
}
]
Please tell me how to add root node JSON. Thanks in advance.
You can do it like this in Java. Create a new JSON object and put your array in it.
JSONObject myobj = new JSONObject();
myobj.put("employees", <your_json_array>);
You could use Jackson annotation JsonRootName:
Annotation similar to XmlRootElement, used to indicate name to use for
root-level wrapping, if wrapping is enabled. Annotation itself does
not indicate that wrapping should be used; but if it is, name used for
serialization should be name specified here, and deserializer will
expect the name as well.
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
And annotate your class as follows:
#JsonRootName(value = "employee")
public static class Employee {
private String address;
private String firstName;
// more... with getters and setters
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Employee
{
public string address { get; set; }
public int phone { get; set; }
}
public partial class Samplepage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Employee> eList = new List<Employee>();
Employee employee = new Employee();
employee.address = "Minal";
employee.phone = 24;
eList.Add(employee);
employee = new Employee();
employee.address = "Santosh";
employee.phone = 24;
eList.Add(employee);
string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);
JArray a = JArray.Parse(ans);
JObject UpdateAccProfile = new JObject(
new JProperty("employee", a)
);
}
}
Related
I have this record interface
public interface EmployeesRecord {
String getName();
String getDepartment();
String getEmail();
}
That is used to fetch the 3-columns rows from a repository query as a list
and I have created a DTO to serve as a response Map<String, List<EmployeesRecord>> where the string is using one of the columns, as a key, to group the results.
public record EmployeesDto(Map<String, List<EmployeesRecord>> employeesRecordList) {
public static EmployeesDto from(List<EmployeesRecord> data) {
Map<String, List<EmployeesRecord>> mappedEmployees =
data.stream().collect(Collectors.groupingBy(EmployeesRecord::getDepartment));
return new EmployeesDto(mappedEmployees);
}
}
My question is after I use the attribute as a key, how do I remove it from the objects responses?
The current response:
{
"employeesRecordList": {
"finance": [
{
"name": "Jerry Doe",
"department": "finance",
"email": "jerry#corp.co"
},
...
{
"name": "Jimmy Doe",
"department": "finance",
"email": "jimmy#corp.co"
}
],
...
"engineering": [
{
"name": "Joe Doe",
"department": "engineering",
"email": "joe#corp.co"
},
...
{
"name": "Joana Doe",
"department": "engineering",
"email": "joana#corp.co"
}
]
}
}
The desired response is the same minus the "department" in the body:
{
"employeesRecordList": {
"finance": [
{
"name": "Jerry Doe",
"email": "jerry#corp.co"
},
...
{
"name": "Jimmy Doe",
"email": "jimmy#corp.co"
}
],
...
"engineering": [
{
"name": "Joe Doe",
"email": "joe#corp.co"
},
...
{
"name": "Joana Doe",
"email": "joana#corp.co"
}
]
}
}
The simplest solution would be to put #JsonIgnore above String getDepartment();
Another solution would be creating a class containing only name and email attributes.
public class EmployeesNameAndEmail {
public String name;
public String email;
public EmployeesNameAndEmail(EmployeesRecord employeesRecord) {
name = employeesRecord.getName();
email = employeesRecord.getEmail();
}
}
Then, the additional mapping should be added after the grouping:
Map<String, List<EmployeesNameAndEmail>> mappedEmployees =
data.stream().collect(
Collectors.groupingBy(
EmployeesRecord::getDepartment,
Collectors.mapping(EmployeesNameAndEmail::new,Collectors.toList())));
I would like to create following json payload from the java classes. Only one condition is there, Subgroup1 can be null, meaning group may/may not have subgroup1. Not sure how can it be done. Any help would be highly appreciated. Thanks in advance! I can change the classes if needed.
{
"data" : [
{
"id": "1",
"name": "ab",
"children": [
{
"id": "1",
"name": "xyz",
"children": [
{ "id": "1",
"name": "opl"
} ]
}
]
},
{
"id":" 2",
"name": "cd",
"children": [
{
"id": "1",
"name": "ijk",
"children": [
{ "id": "1",
"name": "rty"},
{ "id": "2",
"name": "wsc"
} ]
},
{
"id": "2",
"name": "lmn",
"children": [
{ "id": "1",
"name": "qaz"},
{ "id": "2",
"name": "poi"
} ]
},
{
"id": "3",
"name": "opq",
"children": [
{ "id": "1",
"name": "edf"},
{ "id": "2",
"name": "bhgga"
} ]
}
]
},
{
"id": "3",
"name": "ef",
"children": [
{
"id": null,
"name": null,
"children": [
{ "id": "2",
"name": "ijyuht"
} ]
}
]
}
]
}
I have 3 different java classes to map objects.
Data.class
public class Data {
private Long id;
private String name;
private List<Subgroup1> children;
}
Subgroup1.class
public class Subgroup1 {
private Long id;
private String name;
private List<Subgroup2> children;
}
Subgroup2.class
public class Subgroup2 {
private Long id;
private String name;
}
Create Classes structure as below:
public class MainClass {
private List<Datum> data;
}
public class Datum {
private List<Child> children;
private String id;
private String name;
}
public class Child {
private List<Child> children;
private String id;
private String name;
}
below format you can use in Java, its just a way you can do it in multiples way, as i have expained in a easy way.
MainClass mainClass = new MainClass();
List<Child> level2List = new ArrayList<>();
Child level2Child = new Child();
level2Child.setName("opl");
level2Child.setId("1");
level2List.add(level2Child);
List<Child> childList = new ArrayList<>();
Child child = new Child();
child.setChildren(level2List);
child.setId("1");
child.setName("xyz");
childList.add(child);
Datum datum = new Datum();
datum.setChildren(childList);
datum.setId("1");
datum.setName("ab");
List<Datum> datumList = new ArrayList<>();
datumList.add(datum);
mainClass.setData(datumList);
System.out.println(new Gson().toJson(mainClass));
Class:
class Person
{
private String name;
private List<Address> addr;
}
class Address
{
private String street;
private String city;
}
I was able to directly map the person object using #RequestBody attribute however the addr value seem to be null. Is it possible to map this person object directly without instantiating it.
JSON
{
"person" : {
"name": "Bob",
"addr": [
{
"street": "ABC",
"city": "XYZ"
}
]
}
}
I solved it by changing the json a bit.
{
"name": "Bob",
"addr": [
{
"street": "ABC",
"city": "XYZ"
}
]
}
I am trying to retrieve the profilePicture parameter in the LinkedIn liteProfile response. However, for some reason, they return two json objects with the same parameter name (Who even built this API?!).
Response:
{
"firstName": {
"localized": {
"en_US": "Damien"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"lastName": {
"localized": {
"en_US": "Roger"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"profilePicture": {
"displayImage": "urn:li:digitalmediaAsset:C5103AQEGbbhK9i7Qhw",
"displayImage~": {
"paging": {
"count": 10,
"start": 0,
"links": []
},
"elements": [
{
"identifiers": [
{
"identifier": "https://media.licdn.com/dms/image/C5103AQEGbbhK9i7Qhw/profile-displayphoto-shrink_200_200.....",
....
}
}
]
}
}
}
As you may have noticed, in profilePicture, there's two params called displayImage. One with a ~. How do I access this from a java pojo class?
My class looks like this:
public class LinkedInProfileResponse {
public FirstName firstName;
public LastName lastName;
public ProfilePicture profilePicture;
public String id;
public class ProfilePicture {
public String displayImage;
public DisplayImage displayImage;
}
}
The #SerializedName annotation can be used on a field in your POJO to specify the name of the JSON attribute to be mapped to the Java field.
So in your case:
...
#SerializedName("displayImage~)
public DisplayImage displayImage;
...
Trying to serialize a collection of non-primitive types using katharsis, but getting an empty collection all the time.
Response example:
{
"data": {
"type": "products",
"id": "1",
"attributes": {
"simpleAttributes": [
{}
],
"variationGroup": "variationGroup"
},
"relationships": {},
"links": {
"self": "http://localhost:8080/api/products/1"
}
},
"included": []
}
Expected response:
{
"data": {
"type": "products",
"id": "1",
"attributes": {
"simpleAttributes": [
{
tittle: "some title",
value: "some value"
}
],
"variationGroup": "variationGroup"
},
"relationships": {},
"links": {
"self": "http://localhost:8080/api/products/1"
}
},
"included": []
}
Domain objects (getters, setters, constructor and other stuff omitted by using lombok #Data annotation):
#JsonApiResource(type = "products")
#Data
public class Product {
#JsonApiId
private Integer id;
private List<SimpleAttribute> simpleAttributes = new ArrayList<>();
private String variationGroup;
}
#Data
public class SimpleAttribute implements Serializable{
private String title;
private String value;
}
I do not want to use relationships in this case or to include attributes to "included" field. Is it possible in katharsis?
Not sure what actually was wrong, but the problem disappeared after I changed katharsis-spring version from 2.3.0 to 2.3.1.