java swagger 3 annotations #ExampleObject from jsonfile - swagger

I'm documention one of my api with multiple examples like this:
#Operation(summary = "Create new")
#PostMapping("")
public ResponseEntity<Object> createOne(
#Parameter(description = "MyDto")
#io.swagger.v3.oas.annotations.parameters.RequestBody(
content = #Content(examples = {
#ExampleObject(name = "one", value = EXAMPLE_ONE),
#ExampleObject(name = "two", value = EXAMPLE_TWO),
#ExampleObject(name = "three", value = EXAMPLE_THREE)}
))
#RequestBody MyDTO body
) {
...
}
This works fine, though EXAMPLE_ONE is a string value. This is pretty unclear as you can see from the example below
private static final String EXAMPLE_ONE = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";
I looking for a better way to provide the example. A json file would be nice, but I couldn't find anything about that.

You can use externalValue instead of value. See here

Use java text-block instead of normal quoted string
e.g. putting triple double (""")
see https://www.baeldung.com/java-text-blocks

Related

How to Serialize an Object to Json in F# excluding defaults and Keeping Enum Names

I thought this would have been easy but I am having issues ticking all the boxes that I need in this.
I need to
Serialize an object to Json
Ignore any properties not set
Use the ENum names instead of integer values
I have generated all the models for this using the Open API Generator based on a .yaml spec.
My first attempt was to get a bit of code from what looks like an old serializer
let json<'t> (myObj:'t) =
use ms = new MemoryStream()
let serialiser: DataContractJsonSerializer = new DataContractJsonSerializer(typeof<'t>)
let settings: DataContractJsonSerializerSettings = new DataContractJsonSerializerSettings()
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
Encoding.Default.GetString(ms.ToArray())
This function actually does everything fine - except it copiess the enum numbers instead of names and I can't see an option to make this happpen.
My other attempt is using System.Text.Json.JsonSerializer:
let options
= new JsonSerializerOptions(
)
options.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingDefault
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase))
let jsonString:string = JsonSerializer.Serialize(shipmentRequest, options)
I have tried a few different things ( including excluding the Enum converter ) and I always get the following error.
Unable to cast object of type 'System.Int32' to type
'System.Nullable`1[Zimpla.Model.ExpressPackageReference+TypeCodeEnum]'
The specific Object ( roughly ) that it is having an issue with is:
[DataContract(Name = "ExpressPackageReference")]
public partial class ExpressPackageReference : IEquatable<ExpressPackageReference>, IValidatableObject
{
......etc
[DataMember(Name = "typeCode", EmitDefaultValue = false)]
public TypeCodeEnum? typeCode
{
get{ return _typeCode;}
set
{
_typeCode = value;
_flagtypeCode = true;
}
}
This particular property is not even set so it should be skipping over it theoretically. It is possible that I am not generating the object correctly
Without understanding all the details here, I think you are asking how you can serialize an object to json while omitting all properties that are null using System.Text.Json.
To accomplish that you have to set the following option:
options.IgnoreNullValues <- true
Here are the docs for this option:
https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.ignorenullvalues?view=net-5.0#System_Text_Json_JsonSerializerOptions_IgnoreNullValues

Can't serialize records, in F#, with json.net

A very basic example:
type private test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This will produce an empty string.
I have seen that json.net supports F# and that there are a lot of posts related to enum types, etc but I'm not there yet: I'm trying to serialize something very simple.
Many posts point toward another json serializer project, called Chiron, but it was updated a year ago and they're still like:
We’re working on Guides and reference content for working with Chiron, so keep an eye on the Updates
Is there something obvious I haven't seen?
So ideally, working with json.net would be better, especially since I'm used to it in C#
The issue seems to be that Json.Net only serializes public fields of F# records. When you mark the record as private, all its fields also become private and those are ignored. The following works as expected for me:
type test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This produces the expected JSON:
{"a":"hello","b":["1","2"]}

How does the Dart URI class QueryParameters handle Map values?

According to the documentation, it needs to follows the Form Post rules at: https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4. When looking at that information it did not give me much to work with in terms of complex objects or maps.
Right now, If I have a list for example: Each item in the list needs to be stringified.
var params = {"list": [1,2,3]};
// needs to be stringed.
params["list"] = params["list"].map((item)=>item.toString()).toList();
Simple. Also all base items need to be a string as well
var params = {"number": 1, "boolean": true};
params = params.forEach((k,v)=> params[k].toString());
But how do we handle maps?
var params = {"map": {"a":1,"b":"foo","c":false,"d":[]}};
// ??
It seems that after testing in my app and in dart pad, you need to make sure everything is strings, so i am trying to come up with a way to effectively cover lists, maps, and maybe more complex objects for encoding.
var params = {};
params["list"] = [1,2,3];
params["number"] = 1;
params["boolean"] = true;
params["map"] = {"a":1,"b":"foo","c":false,"d":[]};
params.forEach((String key, dynamic value){
if(value is List){
params[key] = value.map((v)=>v.toString()).toList();
}else if(value is Map){
// ????
}else{
params[key] = value.toString();
}
//maybe have an additional one for custom classes, but if they are being passed around they should already have their own JSON Parsing implementations.
}
Ideally, the result of this would be passed into:
Uri myUri = new Uri(queryParameters: params);
and right now, while i solved the list issue, it doesn't like receiving maps. Part of me just wanted to stringify the map as a whole, but i wasn't not sure if there was a better way. I know that when someone accidentally stringified the array, it was not giving me: ?id=1&id=2 but instead ?id=%5B1%2C2%5D which was not correct.
I don't think there is any special support for maps. Query parameters itself is a map from string to string or string to list-of-strings.
Everything else need to be brought into this format first before you can pass it as query parameter.
A simple approach would be to JSON encode the map and pass the resulting string as a single query parameter.

Turn a string into a variable

Hello I have a for in loop where elements is the variable being changed and in this case "elements" is a string but there is a corresponding variable out side of the for in loop that has the same name as the string called elements. So what I mean is out side there is a Var time = [some,text,words] and theres a for in loop that calls a STRING named "time" and I would like to know how to convert the string in the for in loop into the variable by some how taking off the "'s (not that simple I know) without specifically saying "time"(the variable) but instead converting the "elements"(which is the string 'time') string into the variable. I hope I was clear enough if I'm not making sense I'll try again.
You cannot refer to local variables dynamically by their names in Swift. This would break a lot of compiler optimizations as well as type safety if you could.
You can refer to object properties by their names if the class conforms to key-value coding. For example:
class X : NSObject {
let time = ["some", "text", "words"]
func readWordsFromProp(name: String) -> String {
guard let list = self.valueForKey(name) as? [String] else {
return ""
}
var result = ""
for word in list {
result += word
}
return result
}
}
let x = X()
print(x.readWordsFromProp("time"))
In general, there are better ways to do things in Swift using closures that don't rely on fragile name-matching. But KVC can be a very powerful tool

Multiple Searchterm in umbraco Examine Search

I am trying to setup a search in umbraco examine.I have two search fields ,material and manufacturer.when I trying to search with one material and one manufactuere it will give the correct result.but when try to search more than one material or manufacturer it doesn't give the result.here is my code
const string materialSearchFields = "material";
const string manufacturerSearchFields = "manufacturer";
if (!string.IsNullOrEmpty(Request.QueryString["material"]))
{
material = Helper.StripTags(Request.QueryString["material"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["manufacturer"]))
{
manufacturer = Helper.StripTags(Request.QueryString["manufacturer"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["material"]) || !string.IsNullOrEmpty(Request.QueryString["manufacturer"]))
{
var query = userFieldSearchCriteria.Field(materialSearchFields, material).And().Field(manufacturerSearchFields, manufacturer).Compile();
contentResults = contentSearcher.Search(query).ToList();
}
here my search keywors in querystring is material=iron,steel
how can we split this keyword and search done?
Thanks in advance for the help....
You are using the AND operator, in your case I think you are looking for the GROUPEDOR instead?
I was just working in an old project and grabbed this snipet from there (which I've adapted for your needs). I think it's going to help you:
public IEnumerable<DynamicNode> SearchUmbraco(string[] keywords, string currentCulture)
{
// In this case I had some diferent cultures, so this sets the BaseSearchProvider to the given culture parameter. You might not need this, use your default one.
BaseSearchProvider searcher = SetBaseSearchProvider(currentCulture);
var searchCriteria = searcher.CreateSearchCriteria(BooleanOperation.Or);
var groupedQuery = searchCriteria.GroupedOr(new[] {"manufacturer", "material"}, keywords).Compile();
var searchResults = searcher.Search(groupedQuery);
// ... return IEnumerable of dynamic nodes (in this snipet case)
}
I just split(etc) the keywords in an helper and pass them to a string array when I call this method.
Just check this infomation on the umbraco blog: http://umbraco.com/follow-us/blog-archive/2011/9/16/examining-examine.aspx

Resources