REST API object conversion in java - web-services

I have request body of supplier in below format :
{
"supplier": {
"supplierData": {
"supplierAddress": {
"street": "abc",
"postCode": "1234",
"city1": "abcd",
"country": "DE",
"region": "BW"
},
"location": {
"locationID": "1234",
"locationName": "South Africa "
},
"lastUpdatedDateTime": "2022-06-28T10:07:37.000Z"
}
}
}
able to consume it and need to know how to consume the below body request for Location object as null instead of string :
{
"supplier": {
"supplierData": {
"supplierAddress": {
"street": "abc",
"postCode": "1234",
"city1": "abcd",
"country": "DE",
"region": "BW"
},
"location": "null",
"lastUpdatedDateTime": "2022-06-28T10:07:37.000Z"
}
}
}
Any idea how we would do it.

I'm assuming you want to parse this into a defined POJO. And also assuming that Location must be an Object, otherwise (a string), it is null, then you can try parse it:
JSONObject jo = new JSONObject(jsonString); //use your parser library method
Location location = null;
try{
JSONObject jo2 = jo.getJsonObject(location);
//parse jo2 into location
}
catch(JSONException e){
//if exception is throw, it would mean the location data is a string, which can only be "null"
}

Related

How to read solidity function with tuple data in ether-js

When I call the getLandById function in remix it gives the desired result as you can see in the screenshot
Screeshot of remix IDE to get landIdbyId
When I call the same function using ether js. it will gives the output like this :
[ '0.007062190', '-0.01878356', '\x00\x00', [Getter] ]
Instead of
[ '0.007062190', '-0.01878356', '-0.019048060716011,0.007015231577652,-0.018794627684582,0.007386060761845,-0.018423798497481,0.007132627732498,-0.018677231528875,0.006761798548127,-0.019048060716011,0.007015231577652']
I'm struggling to understand how to get the data. Any idea on what should I do to get the desired result? An example would be great.
Ether-js code:
let customHttpProvider = new ethers.providers.JsonRpcProvider(API_URL);
const contract = new ethers.Contract(
Contract_Address,
contractAbi,
customHttpProvider
);
//Calling readOnly Method
async function getLand() {
const getLandById = await contract.getLandById("502");
console.log("Land-Info", getLandById);
}
getLand();
Contract ABIs:
{
"inputs": [
{
"internalType": "uint256",
"name": "landId",
"type": "uint256"
}
],
"name": "getLandById",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
},
{
"internalType": "string",
"name": "",
"type": "string"
},
{
"internalType": "string",
"name": "",
"type": "string"
},
{
"components": [
{
"internalType": "string",
"name": "longitude",
"type": "string"
},
{
"internalType": "string",
"name": "latitude",
"type": "string"
}
],
"internalType": "struct LandContract.PolygonCoordinates[]",
"name": "",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function"
},
Solidity code:
function getLandById(uint landId)
public
view
returns (
string memory,
string memory,
PolygonCoordinates[] memory
)
{
if (!_exists(landId)) {
revert IdNotExist();
}
PolygonCoordinates[] memory coordinates = new PolygonCoordinates[](
land[landId].polygonCoordinates.length
);
for (uint i = 0; i < land[landId].polygonCoordinates.length; ) {
coordinates[i].longitude = land[landId]
.polygonCoordinates[i]
.longitude;
coordinates[i].latitude = land[landId]
.polygonCoordinates[i]
.latitude;
unchecked {
i++;
}
}
return (land[landId].longitude, land[landId].latitude, coordinates);
}
The contract ABI defines 4 output values but your solidity code getLandById() returns only 3 values.

Keyname not found in json

I'm trying to create my own Telegram bot as a project and don't want to use any of the libraries already out there that already do all the hard work for me as I want to do this for myself as on going self learning.
I'm using CPPRESTSDK and trying to get values from the JSON back from telegram.
Here is an example of the JSON
{
"ok": true,
"result": [
{
"update_id": 534699960,
"message": {
"message_id": 159183,
"from": {
"id": HIDDEN,
"is_bot": false,
"first_name": "Hawke",
"username": "XXXXXXXX"
},
"chat": {
"id": HIDDEN,
"title": "CHANNEL_NAME_HIDDEN",
"username": "HIDDEN",
"type": "supergroup"
},
"date": 1548427328,
"text": "Nope, at work"
}
}
]
}
I'm trying to read the text value but I'm getting Keyname not found when trying to access result. The above JSON is stored into a file once retrieving the JSON from telegram.
try {
string_t importFile = U("json.txt");
ifstream_t f(importFile);
stringstream_t s;
json::value v;
if (f) {
s << f.rdbuf();
f.close();
v = json::value::parse(s);
auto results_array = v.at(U("result")).as_array();
}
}
catch (web::json::json_exception& excep) {
std::cout << excep.what();
}

How do I make an User required JSON

I have a JSON file, in that three objects are available, In that 2nd and 3rd objects does not have some fields which I actually needed. In missing fields, I need to add my own values. I will provide my code below
I tried this So far:
with open("final.json") as data1:
a = json.load(data1)
final = []
for item in a:
d = {}
d["AppName"]= item["name"]
d["AppId"] = item["id"]
d["Health"] = item["health"]
d["place1"] = item["cities"][0]["place1"]
d["place2"] = item["cities"][0]["place2"]
print(final)
Error: I am getting Key Error
My Input JSON file has similar data:
[{
"name": "python",
"id": 1234,
"health": "Active",
"cities": {
"place1": "us",
"place2": "newyork"
}
},
{
"name": "java",
"id": 2345,
"health": "Active"
}, {
"name": "python",
"id": 1234
}
]
I am expecting output:
[{
"name": "python",
"id": 1234,
"health": "Active",
"cities": {
"place1": "us",
"place2": "newyork"
}
},
{
"name": "java",
"id": 2345,
"health": "Null",
"cities": {
"place1": "0",
"place2": "0"
}
}, {
"name": "python",
"id": 1234,
"health": "Null",
"cities": {
"place1": "0",
"place2": "0"
}
}
]
I see two issues with the code that you have posted.
First, you are referring to the 'cities' field in you input JSON as if it is a list when it is, in fact, an object.
Second, to handle JSON containing objects which may be missing certain fields, you should use the Python dictionary get method. This method takes a key and an optional value to return if the key is not found (default is None).
for item in a:
d = {}
d["AppName"]= item["name"]
d["AppId"] = item["id"]
d["Health"] = item.get("health", "Null")
d["place1"] = item.get("cities", {}).get("place1", "0")
d["place2"] = item.get("cities", {}).get("place2", "0")

How to create payment profile with the create transaction request on Authorize.net

I would like to create the payment profile with the createTransactionRequest.
Here are the request parameters that i am passing.
{
"createTransactionRequest":{
"merchantAuthentication":{
"name":"***",
"transactionKey":"***"
},
"transactionRequest":{
"transactionType":"authCaptureTransaction",
"amount":"4.95",
"payment":{
"creditCard":{
"cardNumber":"5424000000000015",
"expirationDate":"1217",
"cardCode":123
}
},
"billTo":{
"firstName":"first name",
"lastName":"last name",
"address":"test address",
"city":"test city",
"state":"TX",
"zip":"12345",
"country":"USA"
},
"profile":{
"createProfile":true
}
}
}
}
and here is the response error.
{
"messages":{
"resultCode":"Error",
"message":[
{
"code":"E00003",
"text":"The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'profile' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'shipTo, customerIP, cardholderAuthentication, retail, employeeId, transactionSettings, userFields, surcharge, merchantDescriptor, subMerchant, tip' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
}
]
}
}
The order of the fields in your request matter. They must match what is in the documentation. That means that field needs to come before the billTo field in your JSON:
{
"createTransactionRequest":{
"merchantAuthentication":{
"name":"***",
"transactionKey":"***"
},
"transactionRequest":{
"transactionType":"authCaptureTransaction",
"amount":"4.95",
"payment":{
"creditCard":{
"cardNumber":"5424000000000015",
"expirationDate":"1217",
"cardCode":123
}
},
"profile":{
"createProfile":true
},
"billTo":{
"firstName":"first name",
"lastName":"last name",
"address":"test address",
"city":"test city",
"state":"TX",
"zip":"12345",
"country":"USA"
},
}
}
}
This request yields me this response:
{
"transactionResponse": {
"responseCode": "1",
"authCode": "Y77MQH",
"avsResultCode": "Y",
"cvvResultCode": "P",
"cavvResultCode": "2",
"transId": "40007520179",
"refTransID": "",
"transHash": "94D188D090B695D7C6D47D9293840BE3",
"testRequest": "0",
"accountNumber": "XXXX0015",
"accountType": "MasterCard",
"messages": [
{
"code": "1",
"description": "This transaction has been approved."
}
],
"transHashSha2": "9768048279544EDB22BAAAC194CA3EDBA705FBC569AC9555F3A2A86E545938849CEB2D9519885A4CC69328BBB7DDC36E0852998CAD5FAC1F6CA6427599E3493B"
},
"profileResponse": {
"messages": {
"resultCode": "Error",
"message": [
{
"code": "E00102",
"text": "Customer Info is missing."
}
]
}
},
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
}
}
Looks like you need to add the id field in the customer section:
{
"createTransactionRequest":{
"merchantAuthentication":{
"name":"***",
"transactionKey":"***"
},
"transactionRequest":{
"transactionType":"authCaptureTransaction",
"amount":"4.95",
"payment":{
"creditCard":{
"cardNumber":"5424000000000015",
"expirationDate":"1217",
"cardCode":123
}
},
"profile":{
"createProfile":true
},
"customer":{
"id":<yourIdForThisUser>
},
"billTo":{
"firstName":"first name",
"lastName":"last name",
"address":"test address",
"city":"test city",
"state":"TX",
"zip":"12345",
"country":"USA"
},
}
}
}
That yields:
{
"transactionResponse": {
"responseCode": "1",
"authCode": "SCSVNX",
"avsResultCode": "Y",
"cvvResultCode": "P",
"cavvResultCode": "2",
"transId": "40007520393",
"refTransID": "",
"transHash": "DFB7FE5B8D3FAFE0A18A6B5C125838A3",
"testRequest": "0",
"accountNumber": "XXXX0015",
"accountType": "MasterCard",
"messages": [
{
"code": "1",
"description": "This transaction has been approved."
}
],
"transHashSha2": "57C6A161A948E5A7F5303FCD2FE8CDF3E1D3C38B989161675D47FD61526F3DA9EDBD497169F978860B78A2C5FEC1B6E54807086DF4B0CE346538DDDD9E25C4A8"
},
"profileResponse": {
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
},
"customerProfileId": "1502546960",
"customerPaymentProfileIdList": [
"1502081232"
],
"customerShippingAddressIdList": []
},
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
}
}

AlpacaJS: programmatically change value of TextField after selecting Select

I'm new to AlpacaJS and getting crazy trying to figure out how to do a simple stuff like changing dinamically the content of a text field with the value of a "Select".
The code looks like
$("#form1").alpaca({
"data": {
"name": "Default"
},
"schema": {
"title": "What do you think of Alpaca?",
"type": "object",
"properties": {
"name": {
"type": "string",
"title": "Name"
},
"flavour":{
"type": "select",
"title": "Flavour",
"enum": ["vanilla", "chocolate", "coffee", "strawberry", "mint"]
}
}
},
"options": {
"helper": "Tell us what you think about Alpaca!",
"flavour": {
"type": "select",
"helper": "Select your flavour.",
"optionLabels": ["Vanilla", "Chocolate", "Coffee", "Strawberry", "Mint"]
}
}
},
"postRender": function(control) {
var flavour = control.childrenByPropertyId["flavour"];
var name = control.childrenByPropertyId["name"];
name.subscribe(flavour, function(val) {
alert("Val = " + val);
this.schema.data = val;
this.refresh();
});
}
});
I can see that the function in postRenderer is called (as I can see the alert with relevant value) but (maybe I'm brain dead at this stage) I cannot refresh the text field with that value.
Cheers
I was probably looking at the wrong attribute to be set... After I changed to
this.schema.data = val;
it worked fine :)