How can i exclude Keys in Object which are null to be returned in Json - vb.net

i am wondering if there is a way to prevent a response to return keys in object that are null or null equivalent. I have for example a Response envelope and then the data payload and a sample response looks like this.
{
"success": true,
"errorCode": "",
"message": "JWT Token succesfull created",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidXNlcmlkIiwiU2NvcGUiOlsiQVRUQ1NSIiwiQVRUTFNSIl0sIm5iZiI6MTU4NDc0MjIzMiwiZXhwIjoxNTg0NzQzOTcyLCJpc3MiOiJodHRwOi8vc29hcGFwaS5wZ3RlbC5uZXQiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjU3NDY0In0.dWuETKdlfX4VzwWEP5XafZOpnFmSSCchQHUHi5GZ99E",
"expiration": "0001-01-01T00:00:00",
"scope": null
}
}
In this case expiration and scope are null expiration is a DateTime field.
Here is how i get to this response
Dim myResponse As New jsonResponse
myResponse.success = True
meResponse.errorCode = ""
myResponse.message = "JWT Token succesfull created"
Dim authCheck As New JSONWebTokenUtil
Dim accessList As New List(Of String)
accessList.Add("Sample1")
Dim Token = authCheck.GenerateJSONWebToken("userid", accessList, )
Dim myToken As New tokenResponse
myToken.token = Token
myResponse.data = myToken
Return myResponse
So since in the above case i dont set the scope or experation its null. Is there a way to be part of the out put if null or do i need to check each value and remove it if its null

I would try the following, from vb.net when you recive the json response, add the response to a string variable the with the replace's string method try to change the null value to a new value. I hope this be useful. Thank you. :)

Related

NetCore 3.1 HttpResponseMessage Post([FromBody] return custom XML response

I'm new to creating API's and I'm using Visual Studio 2019. I'm trying to write a simple API that our customer passes XML to us, I save the XML to a file for later processing and return back to the customer a custom XML response that they require. I created a .NetCore 3.1 Microsoft.AspNetCore.Mvc API. The code is simple:
[HttpPost]
[Route("api/Pass_XML_to_BOOMI")]
[Consumes("application/xml")]
public HttpResponseMessage Post([FromBody] XmlDocument IncomingXML)
{
XmlDocument incomingXML = new XmlDocument();
XmlDocument outgoingXML = new XmlDocument();
String payLoadID = Guid.NewGuid().ToString();
String curDate = System.DateTime.Now.ToString();
string INBOUND = IncomingXML.OuterXml.ToString();
string xmlresponse = #"<?xml version=""1.0"" encoding=""UTF-8""?><!DOCTYPE cXML SYSTEM ""http://xml.cXML.org/schemas/cXML/1.1.009/cXML.dtd"">
<cXML payloadID=""" + payLoadID + #""" xml:lang=""en-US"" timestamp=""" + curDate + #"""><Response>
<Status code=""200"" text=""OK""/></Response></cXML>";
outgoingXML.LoadXml(xmlresponse);
//grab order ID number and save to file
string ID = "";
XmlElement element = IncomingXML.SelectSingleNode("cXML/Request/OrderRequest/OrderRequestHeader") as XmlElement;
if (element != null)
{
ID = element.GetAttribute("orderID");
}
string filename = #"f:\" + ID + ".xml";
System.IO.File.WriteAllText(filename, INBOUND);
// Create the response
var response_back = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(outgoingXML.InnerXml, Encoding.UTF8),
};
return response_back;
}
The problem I'm having is when I pass the XML in through Postman all works fine and my file is created but no matter what I try the response back is missing my custom XML (it seems be completely ignoring my Content =) and it is in JSON format, not XML.
Here is how the response comes back in Postman:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"text/plain; charset=utf-8"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
I need to somehow send back an XML response with my custom XML:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.1.009/cXML.dtd">
<cXML payloadID="83dbfb00-22cc-4cb9-9e6b-f34b47f3cbcd" xml:lang="en-US" timestamp="4/2/2022 12:18:49"><Response>
<Status code="200" text="OK"/></Response></cXML>
Does anyone have any idea what I'm doing wrong and how I can accomplish this? Thank you all in advance.

json path for response - API Restassured

Below is the response i get for post call.
How to get quoteId and fee amount value using Json from the below response.
{
"data": {
"quoteId": "Lid123",
"loanTerm": "48.0",
"lenderRate": "4.5",
"customerRate": "4.499999999999904",
"fees": [
{
"feeType": "EstablishmentFee",
"feeAmount": "450"
}
],
"periodPaymentInclGSTAmount": "6416.5"
}
}
Thank you in advance
You can use jsonpath() method to extract value from json.
Response res = ...
String quoteId = res.jsonPath().getString("data.quoteId");
String feeAmount = res.jsonPath().getString("data.fees[0].feeAmount");
System.out.println(quoteId); //Lid123
System.out.println(feeAmount); //450
String id = JsonPath.from(reponseBody).getString("data.quoteId");
String EstablishmentFee = JsonPath.from(reponseBody).getString("data.fees.feeAmount");

How to deserialize the GraphQL server response to object?

How to convert the GraphQL response to object on the client?
I do this way:
var request = new GraphQLRequest
{
Query = #"{customer(id:4){id,firstName,lastName,contact,email}}"
};
var jsonSerializer = new njs.NewtonsoftJsonSerializer();
using var graphQLClient = new GraphQLHttpClient("https://localhost:5011/graphql/", jsonSerializer);
//var response = await graphQLClient.SendQueryAsync<Customer>(request);
var response = await graphQLClient.SendQueryAsync<dynamic>(request);
var graphQLQueryType = #"customer";
var cust = response;//.Data..customer;
var stringResult = response.Data.ToString();
var resultzzz = JsonConvert.DeserializeObject<List<Customer>>(stringResult);
and the result as a string is:
stringResult = "{\r\n "customer": {\r\n "id": "4",\r\n "firstName": "Name#4",\r\n "lastName": "LastName#4",\r\n "contact": "Contact#4",\r\n "email": "you#4#mai.com"\r\n }\r\n}"
It is ok.
But I need to deserialize this response to object class Customer.
and this
var resultzzz = JsonConvert.DeserializeObject(stringResult);
gives me:
ex = {"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[GraphQL.Client.Example.Customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error eith...
`
What I do wrong? How to fix it?

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}

MobileFirst - Invoking Java SQL Adapter adapter procedure

I am following the Java SQL Adapter tutorial for MobileFirst Platform 7.
I'm trying to Get User with userId = "bjones", but I don't know how to set the params {userId} into the procedure /adapters/UserAdapter/{userId}.
function loadUsers(){
busyIndicator.show();
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/", WLResourceRequest.GET);
resourceRequest.setQueryParameter("userId", "bjones");
resourceRequest.send().then(
loadUsersSuccess,
loadUsersFailure
);}
function loadUsersSuccess(result){
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
if (result.responseJSON.length>0)
displayFeeds(result.responseJSON);
else
loadUsersFailure();}
function loadUsersFailure(result){
WL.Logger.error("Feed retrieve failure");
busyIndicator.hide();
WL.SimpleDialog.show("Banking Application", "Service not available. Try again later.",
[{
text : 'Reload',
handler : WL.Client.reloadApp
},
{
text: 'Close',
handler : function() {}
}]
);}
My request is
localhost:10080/JavaAdapters/adapters/UserAdapter/?userId=bjones
but the JSON response contains all user stored in my database
Image for response
In addition, how about the REST call type #PUT, with Path param "userId" and body params: "firstName", "lastName", "password", in order to update an user
From the tutorial the adapter endpoint is /{userId} which means the userId is not a query param but it is part of the url. You need to update your loadUsers function so that it appends the userId at the end of the url, so in your example the fullpath will be /adapters/UserAdapter/bjones
function loadUsers(){
busyIndicator.show();
var usedId = "bjones";
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/"+userId, WLResourceRequest.GET);
resourceRequest.send().then(loadUsersSuccess,loadUsersFailure);
}
UPDATE:
function loadUsersSuccess(result) {
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
// if responseJSON is not null user data was returned
if (result.responseJSON != null) {
displayFeeds(result.responseJSON);
} else{
loadUsersFailure();
}
}
there are basically two type of URL with Parameters:
1. Path parameter:
/adapters/UserAdapter/users/{userId}
2. Query Parameter:
/adapters/UserAdapter/users?userId={userId}
java adapter with query parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users")
public String getuserById(#QueryParam("userID") String userId)
{
System.out.println(userId);
}
java adapter with path parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users/{userId}")
public String getuserById(#PathParam("userId") String userId)
{
System.out.println(userId);
}
I hope, second example answers your question in java adapter.