I am sending the following response from server :
return new OperationResult.Created { CreatedResourceUrl = getURI(newDuplicateKfEntity), ResponseResource = newDuplicateKfEntity };
My question is how can I get this CreatedResourceUrl object in my javascript??
Instead of OperationResult.Created return a typed DTO and use a Codec to encode it as Json. After that consuming Json in JavaScript is simple.
Related
A TypeScript application sends a Uint8Array object through an HTTP POST request to a Scala Play application.
How to convert the Uint8Array object into a Scala object in the Play application?
For example, the TypeScript code sends the following object:
{stuff: new Uint8Array([0, 1, 2])}
Inside the Scala Play controller:
case class StuffData(stuff: List[Byte])
implicit val reads: Reads[StuffData] = Json.reads[StuffData]
def processStuff = Action.async(parse.json[StuffData]) { request =>
val stuffData = request.body
println(stuffData)
}
This does not work... the error message from Play is:
For request 'POST /send-stuff'
[Json validation error List((obj.key,List(JsonValidationError(List(error.expected.jsarray),WrappedArray()))))]
By default, Unit8Array is encoded in JSON as {"0":1,"1":2,"2":3,"3":4}, so you can decode it in Scala as a Map or write your custom reader, that can translate this object into an array type. Or you could make changes from the other side, instead of using Uint8Array you can use an array or a custom stringify function that makes expected JSON.
In my opinion, the easiest one is writing the custom reader. Custom reader example:
implicit val stuffReader = new Reads[StuffData] {
def reads(js: JsValue): JsResult[StuffData] = {
JsSuccess(StuffData(
(js \ "stuff").as[Map[String, Int]].toList.map(_._2)
))
}
}
I make an API from Laravel and check the 'Get' request from Postman where it will return as follow:
"answer_selected": "{1:\"True\",2:\"False\"}"
Then, the Flutter application will read the JSON and serialize it using the model class.
Are there any ways to convert the value of "answer_selected" to map<int, dynamic>? Or, my JSON API response format is incorrect?
You should not return a string that is not a complete JSON. Either return
{"answer_selected": {1:"True",2:"False"}}
or
{1:"True",2:"False"}
will be much better. jsonDecode in dart supports decode to map<String, dynamic, and the key in JSON must be string too. So the JSON should like
{"1":"True","2":"False"}
If you want to transform it to map<int, dynamic>, just do
void test() {
String text = '{"1":"True","2":"False"}';
Map<String, dynamic> map = jsonDecode(text);
Map<int, dynamic> desiredMap =
map.map((key, value) => MapEntry(int.parse(key), value));
desiredMap.entries.forEach((element) {
print('${element.key} ${element.value}');
});
}
I'm working on a project and I need to send simple requests from a Python backend to a JavaScript App. I have a simple array with names ["x", "y", "z"] and I send it serialized over the socket but when I receive it I don't know how to parse it in a simple array format, not JSON format.
The code should be something like this
websocket.onmessage = function(event){
const receivedMessage = someParses.deserialize(format, event.data);
console.log(receivedMessage);
}
``
JSON.parse is for both JSON & array
for example
inputOfJsonString ='{"age":12,"name":"Mrx"}'
JSON.parse(inputOfJsonString)
=> {age: 12, name: "Mrx"}
anotherInputOfArrayString ="[12,13]"
JSON.parse(anotherInputOfArrayString)
=> [12,13]
Can you post the sample serialize string you are receiving in event.data as the serialization techniques in JS may very you can use
JSON.parse( string, modifierfunction )
and depending upon the response you receive can apply a modifier function
I used json.dumps() to format the array in python and it works now. Thanks
I am calling a REST API in my project for creating some records.
Everything is working fine but I got a challenge, the JSON request body is too big (having thousands of keys and values).
Now I want to compress the request body. I tried it using JavaScript
var reqJSON = { ... } // too big JSON object
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
Now I am sending the string in the request body and converting this string into JSON at the server-side.
I am curious, is it the correct way of JSON compression? If yes how can I check the difference in the request body size?
Thanks for your time.
That isn't compression at all.
var reqJSON = { ... } // too big JSON object
That will give you a JavaScript object, not JSON. Possibly your Ajax library will convert it to JSON if you pass it. There's no way for us to know. If the data is to get to the server then it will need serializing to some format that can be sent over the wire so something must be converting it before the HTTP request is made.
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
That will give you JSON. There's no compression involved though.
If you want to compress it then you'd need to look for a library that can do actual compression.
You can use gzip for compress json its working fine
I'm getting a json response from the forecast.io api with
JSON.parse(open("https://api.forecast.io/forecast/api-key/latitude,longitude").read)
And it looks like this
{"latitude"=>58.5942,
"longitude"=>16.1826,
"timezone"=>"Europe/Stockholm",
"offset"=>2,
"currently"=>{
"time"=>1367829429,
"summary"=>"Clear",
"icon"=>"clear-day",
"precipIntensity"=>0,
"temperature"=>59.04,
"dewPoint"=>41.6,
"windSpeed"=>11.49,
"windBearing"=>224,
"cloudCover"=>0.08,
"humidity"=>0.53,
"pressure"=>1022.88,
"visibility"=>6.21,
"ozone"=>319.4
}
I'm new to json but this is not regular json right? What should I do to get this to my view in script tags?
Thanks.
Use the particular JSON Keymap you want in the call, and return it in the JSON request callback function. I believe that would resolve your problem.
response = HTTParty.get('https://api.forecast.io/forecast/api-key/latitude,longitude', {:timeout => 3})
#currenttemp = response["temp"]
it will return in a json object because it detects it is JSON. (HTTParty is just a helper gem)