I am new to using springboot and swagger, so not very familiar with this stuff. But what I want to do is to input a JSONArray into a swagger API and get the input into a controller. So, I have the following controller code:
#RestController
public class NameRegisterController{
#Autowired
private NameRegisterService service;
#Postmapping(path="/control")
public void NameRegisterAdd(#RequestParam JSONArray NameList)
{
service.addNames(NameList);
}
}
Here, addNames is a function which takes JSONArray as input. When I go to the swagger API, I add the input as:
["name1","name2","name3"]
Unfortunately, when I execute, I get the error
"ConversionFailedException: Failed to convert from type[java.lang.String] to type [#org.springframework.web.bind.RequestParam org.json.JSONArray] for value 'name1'; nested exception is org.json.JSONException: JSONArray test must start with '[' at 1 [character 2 line 1"
I don't get it because the first character of my input is "[" as put in the swagger API. Would be very grateful if someone can provide some help.
My swagger is in my work environment, so am inserting similar pictures from the internet.
The first pic is what I get. The second pic is what I want
String Array
Frontend Pass with HTTP request
[“a”,”b”,”c”]
Backend receive in controller methods
#RequestParam String[] ids
#RequestParam List<String> ids
And I dont see you defining which request parameter name it should be looking at?
Example:
public String inputControllerMethod(#RequestParam(value="myParam") List<String> myParam){
}
=== Edited ===
You can't.
Using the [Add String Item] button you must insert 1 String at a time.
However if they are not Strings, but rather an Array of Objects, then swagger allows you to write the array:
Use this https://editor.swagger.io/#/ to see an example.
Documentation: https://swagger.io/docs/specification/2-0/describing-parameters/
Your other option also if you really dont want the user to enter and you are limited by specific options is an enum:
parameters:
- name: "status"
in: "query"
description: "Status values that need to be considered for filter"
required: true
type: "array"
items:
type: "string"
enum:
- "placed"
- "approved"
Then the user simply selects multiple/all options:
Related
I am currently working on a school project. We have a series of response templates in JSON format that will take values from the request and then return it accordingly in the response when run in postman.
e.g
Request:
{
"Application_id":123456
}
Response:
{ "Application_id: 123456, TIMESTAMP: 20220501}
I am able to get these values in the response but the issue I am running accross now is figuring out how to combine 2 values in the request into one like so:
Request:
{
"Application_id":123456
"user_id_first_six": 456789
"user_id_last_four": 1234
}
Expected Response:
{ "Application_id: 123456, TIMESTAMP: 20220501, combined_id:456789****1234}
what I have tried is to put combined_id : "user_id_first_six"+******+"user_id_last_four" but this doesnt work.
Apologies if I cant be more specific as there are portions that I have left out due to confidentiality issues.
The easiest way to achieve this in Java would be to use JSONObject. In your Request-Handler, add two parameters of Type JSONObject and then merge them:
jsonObj.putAll(jsonObj1)
Thanks all for the guidance. I basically did what Knu8 suggested and extracted the values using Matcher+Regex (<(.*)>)(\W*)(<(.*)>) and converted them to strings and then used StringBuilder to append all the components together.
I am taking a JSON file as input for a class and parsing the values using gson through respective data classes.
I want to call a function that takes a String value as an argument.
The string value allowed is decided from the values parsed from JSON file. Can I somehow check for that string value passed to the function at compile-time & give an error at compile-time?
Or If I can allow only certain values in the argument for the function based on the values from JSON
Detailed Explanation of use case:
I am building a SDK in which a the person using sdk inputs json String. The json is standardised and is parsed in my code.
{
"name": "Test",
"objects": [
{
"name": "object1",
"type": "object1"
}
]
}
Here name values and other values may vary based on the input by the developer using it but key remains same. But we need to call a function using the value in objects name parameter.
fun testMethod(objectName:String)
So developer calls the testMethod as testMethod(object1).
I need to validate object1 parameter based on json but is there any way possible restricting the test method parameter to object1 only & give error at compile time if the developer calls testMethod(obj1)
Right now I parse JSON & have checks inside the testMethod()
Sure it's possible to do, but somehow in different way, that you described. First of all, as you already mentioned this behavior could be done easily. For this purpose we have Objects.requireNotNull() or Guava.Preconditions(). At the same way you can define you checking but this will work on runtime only.
To do in compile time, you need to create Annotation Preprocessor. The same, as did in different libraries, and one of them, could be Lombok, with their NotNull and Nullable. Android annotation just provide mark and bound for IDE warning, but in their case they adding NotNull checking and throw exception for every annotation usage during compile time.
It's not an easy way, but it's what you are looking for.
No, it's impossible check it in compiler time. It's string handling, as numeric calculation.
In my app, I convert string to JSON and JSON to string, passing class descriptor. My aim is record JSON string in a text file to load in SQLite database. This code I've run in my desktop computer not in Android.
data class calcDescr (
...
)
val calc = CalcDescr(...)
// toJson: internal Kotlin data to JSON
val content = Gson().toJson(calc)
//==================
// Testing validity
// ================
// fromJson: JSON to internal Kotlin data.
// It needs pass the class descriptor. Uses *Java* token, but it's *Kotlin*
var testModel = Gson().fromJson(content, CalcDescr::class.java)
// toJson: internal Kotlin data to JSON again
var contentAgain = Gson().toJson(testModel)
// shoul be equal!
if (content == contentAgain) println("***ok***")
In my file, I write the variable content in a file
I am trying to call the REST Webservices PATCH API, here is My JSON payload
[
{ "op":"replace", "path":"/values/Timestamp","value":"2016-10-28T15:25:43.511Z"},
{ "op":"replace", "path":"/values/Flag", "value":true },
{ "op":"replace", "path":"/values/Flow", "value":"Flow A"},
{"op":"replace", "path":"/values/Interests", "value":[ "Sports", "Book Reading" ] }
]
JSON Value attribute has different values with different data types. and I want to prepare Entity object(Java) and convert it into JSON and call REST end point.
now
I am not very sure
which is the best suitable data type I can choose for values attribute
I have referred following links but I didn't get enough details
Android REST API using PATCH method
https://www.rfc-editor.org/rfc/rfc5789#section-2.1
http://blog.earaya.com/blog/2013/05/30/the-right-way-to-do-rest-updates/
http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/
but I didn't get enough details.
any suggestion on this is really appriciated
Got the java object from the client and created another Java class with below properties and set the values
opn - string
path - String
value - Object
added above java objects to array list then used the GSON library to convert it into the array of JSON objects which will be accepted by patch api.
and please note the content type is application/json-patch+json
I'm having some troubles with different back-end processing of POST rest calls. I have two different objects which are updated through two different POST methods in my back-end. I catch the objects as a JsonNode, and in order to parse the attributes which I need to update, i create an iterator like so :
final Iterator<String> fieldNames = attributes.fieldNames();
The problem comes when I send my data from angular, in one case I need to explicitly send it like angular.toJson(data) in order to properly grab all the field names, and in the other case I just send the data (without the angular json conversion). Why is this behavior occurring ? Does this have to do with how I create the $http post call ? Here are the two different calls from angular:
$http.post(URL, angular.toJson(data)).success(function(data){
/*whatever*/ }).error(function(data) {
/*whatever*/ });
//Second call looks like this
var promise = $http({method: 'POST', url:URL, data:data, cache:'false'});
//this one i resolve using $q.all
I truncated the code to just the important stuff. My data is created like this currently(tried multiple ways in order to skip the need for toJson):
var data = "{\"Attribute1:\"+"\""+$scope.value1+"\","+
"\"Attribute2:\"+"\""+$scope.value2+"\"}";
How do I need to send the json data in order for it to correctly be converted to a JsonNode in my back-end, so I can properly iterate the fieldNames ?
I did manage to come to a common solution which consumes the json correctly in my back-end. I declared my json objects in angular like this :
$scope.dataToSend = {
"SomeAttribute" : "",
"SomeOtherAttribute" : ""
};
And then added my values like so :
$scope.dataTosend.SomeAttribute = someValue;
$scope.dataTosend.SomeOtherAttribute = someOtherValue;
No longer need to send the data with angular.toJson().
I read all my likes using FQL with Spring Social Facebook
here is the method:
public List<LikeObject> startF(String token){
Facebook facebook = new FacebookTemplate(token);
FacebookProfile profile = facebook.userOperations().getUserProfile();
//System.out.println(facebook.isAuthorized());
System.out.println("Authenticcated user: "+profile.getFirstName()+" "+profile.getLastName());
PagedList<String> friendListIds = facebook.friendOperations().getFriendIds();
List<LikeObject> resultsLikes = facebook.fqlOperations().query("SELECT object_id, object_id_cursor,object_type, post_id, post_id_cursor, user_id "+
"FROM like "+
"WHERE user_id =me() ", new FqlResultMapper<LikeObject>(){
public LikeObject mapObject(FqlResult result) {
LikeObject like = new LikeObject();
like.object_id = result.getString("object_id");
like.object_id_cursor = result.getString("object_id_cursor");
like.object_type = result.getString("object_type");
like.post_id = result.getString("post_id");
like.post_id_cursor = result.getString("post_id_cursor");
like.user_id = result.getString("user_id");
return like;
}
});
return resultsLikes;
}
Here results:
LikeObject [object_id=578416.., object_id_cursor=null,
object_type=status, post_id=, post_id_cursor=null, user_id=10217..]
Then I would like to parse like.object_id and convert it to java object. But I've no idea how to do it using spring social facebook.
I've tried facebook.fetchObject(like.object_id, PostType.STATUS) . But it seems to be a wrong way.
Is there any possible way to parse an "object_id" in spring social without parsing raw JSON response from GET query?
I've tried this:
LinkPost post = facebook.fetchObject(obj_id, LinkPost.class);
I believe that obj_id has type link, I've checked it
and it cause following exception:
Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'postType' that is to contain type id (for class org.springframework.social.facebook.api.LinkPost)
at [Source: java.io.ByteArrayInputStream#6ca79a6a; line: 1, column: 11114]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'postType' that is to contain type id (for class org.springframework.social.facebook.api.LinkPost)
at [Source: java.io.ByteArrayInputStream#6ca79a6a; line: 1, column: 11114]
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:171)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:163)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:94)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:228)
at org.springframework.social.facebook.api.impl.FacebookTemplate.fetchObject(FacebookTemplate.java:202)
at com.repost.facebook.FbConnection.getLikedPosts(FbConnection.java:58)
at com.repost.facebook.MainClass.main(MainClass.java:15)
I'm still unclear what you mean by "parse". But let me attempt to answer this anyway...
I think you simply want to be able to fetch the object as a Post (or LinkPost) object...is that right? If so, then there's some special magic that I unfortunately had to bake into the API to be able to both grab the post type and do polymorphic deserialization into a specific type of Post (e.g., LinkPost, StatusPost, etc).
You can see the setup taking place in https://github.com/SpringSource/spring-social-facebook/blob/master/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/FeedTemplate.java. In the deserializePost() method, you see that I read the "type" property and copy it into a new "postType" field. One of those fields is used to populate the Post's type property and the other is used to determine which specific subclass of Post should be created. It's a hack to work around a problem I had with Jackson 1.9.x...I think that Jackson 2 will make that hack unnecessary, but I've not tried it yet.
Therefore, I see only one practical way of doing this: Don't do all the work yourself. Instead use facebook.feedOperations().getPost(objectId). It knows how to do the magic under the covers to give you a Post object. From there, if you know the specific kind of Post, you can cast it as (and if) needed to LinkPost, StatusPost, etc.
The only other option I see is to go even lower level and make the request through facebook.restOperations() and to handle the binding for yourself. That's obviously a lot more work on your part.