I'm using renderJSON() method to return an array of objects, with a custom JsonSerializer for the class of each element. The response has the following format:
[{"id":2,"name":"fred"},{...},...]
But I would like to add the name of the array at the begginning:
"arrayname":[{"id":2,"name":"fred"},{...},...]
How can I add the name of the object to a JSON response with renderJSON()? Should I use a template or can I do it with java code?
"arrayname":[{"id":2,"name":"fred"},{...},...]
looks like invalid Json, but if you wrap the array in an object you could get:
{"arrayname":[{"id":2,"name":"fred"},{...},...]}
E.g. something like this:
public class MyArrayWrapper {
public final User[] arrayname;
public MyArrayWrapper(User[] arrayname) {
this.arrayname = arrayname;
}
}
Then you can call renderJSON(new MyArrayWrapper(yourUserArray)); to get JSON like:
{"arrayname":[{"id":2,"name":"fred"},{...},...]}
Or just return as a list Arrays.asList(arr);
Related
Desired request:
http://localhost:8080/values?input=[["aaa","bbb","ccc","ddd"],["abcd","abcd","abcd","abcd"]]
I would love to be able to pass the URL in some way using brackets.
However if it is not possible, how do I still pass the list of lists ?
My controller path:
#GetMapping(path = "/values/")
public String getValues(#RequestParam List<List<#Size(min=4, max=4)String>> input) {
return input.get(0).get(2);
}
which should return ccc.
This is not a good way to do this job. Instead you can pass them as request parameter and and receive them from hashMap. But since you are passing list of lists, so it would be convenient to pass them in request body. To do that you have to create a request POJO class following these steps:
public class ListRequest{
private List<List<String>> inputList;
//generate getter, setter for it
}
Now, change in your controller, replace GET method with POST:
#PostMapping(path = "/values/")
public String getValues(#RequestBody ListRequest input) {
List<List<String>> yourData=input;
System.out.println(yourData);
//operate on your data as you wish
return input.get(0).get(2);
}
Create a Pojo class with a list of list as field.
Send the values in the request body and use a post method.
In the controller method, use this Pojo object to retrieve those values.
I am trying to create Dto class in Java for a json which is similar to this.
{
"abcList":[
{
"keyA":"valA",
"lstB":[{
"keyC":"valC"
},{
"keyC":"valC1"
}]
},{
"keyA":"valA",
"lstB":{
"keyC":"valC2"
}
}
]
}
Is the Json even valid? Inside the list abcList, the first object has a list "lstB" and in the second object, the field "lstB" is not a list.
If the json is valid, how would I create the corresponding Java Classes?
This does not work.
class TopObject{
List<ABC> abcList;
}
class ABC{
public String keyA;
public List<B> lstB;
}
class B{
public String keyC;
}
I mean I can parse it successfully with gson, iterating through every element of the json with a code like below,
if(lstB.isJsonArray()){
System.out.println("lstb is array");
List<B> arLstB = parseBArray(lstB);
abc.setLstB(arLstB);
}else{
System.out.println("lstb is not array");
B b = parseB(lstB);
abc.addB(b);
}
but the original json is very large and i will end up writing the iterating logic for days. I want a solution where I can annotate it properly and do the mapping in one shot like this.
gson.fromJson(jsonInString, TopObject.class);
Right now I am using Gson to deserialize JSON to Object.
The JSON looks like this:
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":"{\"C_FirstName\":\"\",\"ContactID\":\"2776967\",\"C_LastName\":\"\"}",
"queueDate":"2016-06-28T01:03:36"
}
]
And my entity object looks like this:
public class AppCldFrmContact {
public String hash;
public String instanceid;
public HashMap<String,String> text;
public String queueDate;
}
If text was a String data type, everything would be fine. But then I wouldn't be able to access different fields as I want to.
Is there a way to convert given JSON to Object I want?
The error I am getting is: Expected BEGIN_OBJECT but was STRING at line 1 column 174, which is understandable if it cannot parse it.
The code doing the parsing:
Type listType = new TypeToken<List<AppCldFrmContact>>() {
}.getType();
List<AppCldFrmContact> contacts = gson.fromJson(response.body, listType);
For you expected result, JSON data should be like below format,
[
{
"hash":"c8b2ce0aacede58da5d2b82225efb3b7",
"instanceid":"aa49882f-4534-4add-998c-09af078595d1",
"text":{"C_FirstName":"","ContactID":"2776967","C_LastName":""},
"queueDate":"2016-06-28T01:03:36"
}
]
You are getting this error because text field is a JSON map serialized to the string. If it is an actual your data and not a just an example, you can annotate a field with #JsonDeserialize and write your own custom JsonDeserializer<HashMap<String,String>> which will make deserialization 2 times.
I have a web service that sends a JSON similar to this one:
[
"4.11.3",
"4.10.7",
"4.10.2",
"4.9.1"
]
My Rest interface looks like this:
#Rest(...)
public interface RestInterface {
#Get("...")
String[] getVersions();
}
But I always get null as return value. Could someone help me please?
your json is a json-array of length 4 containing strings
so .... use following code :
JSONArray versionJsonArray=new JSONArray(<web-service response>);
String[] versionString=new String[versionJsonArray.length()];
for(int j=0;j<versionJsonArray.length();j++)
versionString[j]=versionJsonArray.getString(j);
Add this to your rest service:
#Accept(MediaType.APPLICATION_JSON)
Rest(...)
public interface RestInterface {
#Get("...")
JSONArray getVersions();
}
let the rest adapter type the string into a json array.
I have a REST api GET call that takes an array of strings formatted as JSON. I'd like to use Jersey to convert that array of strings to something like a string array or List. I've reviewed http://jersey.java.net/nonav/documentation/latest/json.html, but it looks like Jersey wants me to create an object that specifies how it should be mapped, which I really don't want to do because it's just a simple array.
#GET
public Response get(#QueryParam("json_items") String requestedItems) throws IOException
{
//Would like to convert requestedItems to an array of strings or list
}
I know there are lots of libraries for this - but I'd prefer to use Jersey and not introduce any new libraries.
Create a wrapper object for you data (in this case the Person class) and annotate it with #XMLRootElement
Your post method should look like this
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void post(List<Person> people) {
//notice no annotation on the method param
dao.putAll(people);
//do what you want with this method
//also best to return a Response obj and such
}
this is the right way to do this stuff where the data is sent in the request.
but if you want to have a QueryParam as the JSON data you can do this
say your request param looks like this:
String persons = "{\"person\":[{\"email\":\"asdasd#gmail.com\",\"name\":\"asdasd\"},{\"email\":\"Dan#gmail.com\",\"name\":\"Dan\"},{\"email\":\"Ion#gmail.com\",\"name\":\"dsadsa\"},{\"email\":\"Dan#gmail.com\",\"name\":\"ertert\"},{\"email\":\"Ion#gmail.com\",\"name\":\"Ion\"}]}";
you notice that its a JSONObject named "person" that contains a JSONArray of other JSONObjets of type Person with name an email :P
you can itterate over them like this:
try {
JSONObject request = new JSONObject(persons);
JSONArray arr = request.getJSONArray("person");
for(int i=0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o.getString("name"));
System.out.println(o.getString("email"));
}
} catch (JSONException ex) {
Logger.getLogger(JSONTest.class.getName()).log(Level.SEVERE, null, ex);
}
sry
Just try to add to your Response the array, like
return Response.ok(myArray).build();
and see what happen.
If it's just a very simple array it should be parsed without any problem.
EDIT:
If you want to receive it then just accept an array instead of a String. Try with a List or something like this.
Otherwise you can try to parse it using an ObjectMapper
mapper.readValue(string, List.class);