How to replace query parameters into intercalated url? - asp.net-core

Hello i am want to know given a an url saved as a string with placeholders.Is there anyway to just replace the spaceholders with the desired values?
public string Constant= #"/main/url/[id]/something/[value]";
public string Replace(int id,string value)
{
string url=Replace(id,value,Constant); // "/main/url/3/something/abc"
}
As you can see the url is intercalated with variables.Is there any class provided by the framework that i could use like:
public class Replacer
{
public string FillUrl(List<object> variables,string url)
{
var fullUrl=Replace(variables,url);
return fullUrl;
}
}

You can use the String.Replace (docs):
Returns a new string in which all occurrences of a specified Unicode
character or String in the current string are replaced with another
specified Unicode character or String.
public string Replace (string oldValue, string newValue);
url = url.Replace("[id]", id.ToString()).Replace('[value]', value);

Related

RESTFUL Web Service using multiple arguments

I have a class with my getters and setters, containing values, for example:
String value1;
String value2;
double result;
I want to use these two strings to determine what should happen with the result. If value1 equals "one" and value2 = "two" then the result should be multiplied by a predefined value.
#GET
#Path("/{value1}/{value2}/{result}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public double getResult() {
Something mon = new Something();
mon.setOne(22.2);
mon.setTwo(11.1);
if("/{value1}".equals("one")){
//multiply by mon.setOne;
}
return 0;
}
How do I read and access the values defined in the path?
If you want to receive the values as path parameters (like /foo/one/two/something), you can use #PathParam:
#GET
#Path("/foo/{value1}/{value2}/{result}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public double getResult(#PathParam("value1") String value1,
#PathParam("value2") String value2,
#PathParam("result") String result) {
...
}
But, depending on what you intend to do, you could consider using query parameters (like /foo?value1=one&value2=two&result=something) with #QueryParam:
#GET
#Path("/foo")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public double getResult(#QueryParam("value1") String value1,
#QueryParam("value2") String value2,
#QueryParam("result") String result) {
...
}
You may want to check the answers to this question for details on when to use each of them.
First of all you should use a unique API name I used /GetResult then put the parameter.
#GET
#Path("/GetResult/{value1}/{value2}/{result}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public double getResult(
#PathParam(value = "value1") String value1,
#PathParam(value = "value2") String value2,
#PathParam(value = "result") String result) {
if (value1.equals("one")) {
}
return 0;
}

Converting a JSON String To an ArrayList of Objects with GSON

We have the following json string:
jsonUserDataRecs=[{"G_ID1":1,"G_ID2":2,"G_ID3":3,"NAME":"g1"},{"G_ID1":4,"G_ID2":5,"G_ID3":5,"NAME":"g2"}]
Would like to convert it into the following data type:
ArrayList<USER_DATA_REC> userDataRecs;
We tried the following, but did not get any results:
userDataRecs = gson.fromJson(jsonUserDataRecs, new TypeToken<ArrayList<USER_DATA_REC>>() {}.getType());
When we run : userDataRecs.get(0).getNAME(), we did not get any results.
Any help will be greatly appreciated.
Thank you.
First make a POJO class:
public class UserDataRecord {
public int G_ID1;
public int G_ID2;
public int G_ID3;
public String NAME;
public String getNAME() {
return NAME;
}
}
Next use gson to deserialize your json string like so:
UserDataRecord[] userDataRecords = gson.fromJson(jsonUserDataRecs, UserDataRecord[].class);
Now you have an array of the deserialized user data records. You can manually convert this to a list if you need to, or just iterate it using a normal for loop.

How to retrive #Test method parameters in #DataProvider method?

I would like to retrieve parameters name of Test method in DataProvider method.
By using method.getParameterTypes() in DataProvider, I am able to get the class of param being passed in Test method, but I want the names.
#Test
public void TC_001(String userName, String passWord){
//code goes here
}
#DataProvider
public Object[][] testData(Method method){
//Here I want to get names of param of test method i.e. userName and passWord
}
This is required because using these names I can get the data from my Excel file
You can use reflection to get the parameters from the method to get the parameter names.
#DataProvider
public Object[][] testData(Method method){
String arg0 = method.getParameters()[0].getName();
// should be "userName" in your example test case
}
Note that the classes have to be compiled with -g:vars to include the parameter names in the debug information. Otherwise parameter names are named arg0, arg1, ... It appears that with the OpenJDK 8 this is the default.
To be less dependant on that fact and to avoid possible name confusion/conflicts I'd use a (custom) annotation that specifies the argument name:
Define an annotation:
#Retention(RUNTIME)
#Target(PARAMETER)
public #interface ParamName {
public String value();
}
Use it:
public void TC_001(#ParamName("username") String userName, String passWord) { ... }
Access the name:
Parameter parameter = method.getParameters()[0];
ParamName parameterNameAnn = parameter[0].getAnnotation(ParamName.class);
String parameterName;
if (parameterNameAnn != null) {
// get the annotated name
parameterName = parameterNameAnn.value();
} else {
// annotation missing, resort to the "reflected" name
parameterName = parameter.getName();
}
See also
Reflection Tutorial (Oracle)
Especially Parameter Reflection (Oracle)
Compiler options (Oracle)
Annotation Tutorial (Oracle)

Formatting Html strings to be used in HtmlHelper extensions -MVC

I wrote an extension method :
public static string XDropDown(this HtmlHelper helper,string name, string optionLabel,object selectedValue)
{
StringBuilder b = new StringBuilder();
b.AppendFormat("<select name='{0}' id='{0}'>", name);
b.Append("</select>");
return b.ToString();
}
The rendered version :
<select name='CCName' id='CCName'><option value=&quot;BT&quot;>Bhutan</option></select>
and I am using it from a partial view,
it isn't rendered as it's expected,
I know that I can use Tag builders also,
but eager to know weather if this could work somehow or not.
Use the MvcHtmlString as the return type like so:
public static MvcHtmlString XDropDown(
this HtmlHelper helper,
string name,
string optionLabel,
object selectedValue)
{
StringBuilder b = new StringBuilder();
b.AppendFormat("<select name='{0}' id='{0}'>", name);
b.Append("</select>");
return MvcHtmlString.Create(b.ToString());
}

Jackson : Conditional select the fields

I have a scenario where i need to use the payload as
{"authType":"PDS"}
or
{"authType":"xyz","authType2":"abc",}
or
{"authType":"xyz","authType2":"abc","authType3":"123"}
or
any combination except for null values.
referring to the code i have 3 fields but only not null value fields be used.
Basically i don't want to include the field which has null value.
Are there any annotations to be used to get it done
public class AuthJSONRequest {
private String authType;
private String authType2;
private String authType3;
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getAuthType2() {
return authType2;
}
public void setAuthType2(String authType2) {
this.authType2 = authType2;
}
public String getAuthType3() {
return authType3;
}
public void setAuthType3(String authType3) {
this.authType3 = authType3;
}
}
Try JSON Views? See this or this. Or for more filtering features, see this blog entry (Json Filters for example).
This is exactly what the annotation #JsonInclude in Jackson2 and #JsonSerialize in Jackson are meant for.
If you want a property to show up only when it is not equal to null, add #JsonInclude(Include.NON_NULL) resp. #JsonSerialize(include=Include.NON_NULL).