Kotlin http4k read response as JSONObject (org.json) - json

As a beginner to kotlin and http4k, I am trying to read json response of a build job in jenkins. The sample code I have is as follows
val request = Request(Method.GET, "https://myjenkins.com/api/json")
.header("Authorization", "Basic "+Base64.getEncoder().encodeToString("username:token".toByteArray()))
val client: HttpHandler = ApacheClient()
println(client(request))
I am looking for a way to read the Response from client(request) as a org.json.JSONObject so I can just read the values from it.
I am looking for some pointers that would help me out to understand how to do this.

Related

JMeter: Update Empty JSON hashmap groovy

Response from http request:
{"Preferredvalue":{"notations":[]}}
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
I am able to get up to notations and also the size.
If the size is 0, I want to update the notations as below
{"Preferredvalue":{"notations":[{"Name":${firstName},"lName":${lastName}}]}
firstName and lastName are Jmeter variable which are fetched from another calls, and I want to use these values in my another call and send a PUT request.
Searched a lot but couldnt find an answer :(
Best,
Something like:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def notations = response.Preferredvalue.notations
if (notations.size() == 0) {
notations.add([Name: vars.get('firstName'), lName: vars.get('lastName')])
}
def request = new groovy.json.JsonBuilder(response).toPrettyString()
vars.put('request', request)
should do the trick for you. Refer generated value as ${request} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

Micronaut post json body using RxHttpClient

How to execute a post call in Micronaut having a json body. The execute method is below but how do we pass json and make this work.
HttpRequest<String> httpRequest = new SimpleHttpRequest<String>(HttpMethod.POST, "https://someurl", json);
return rxHttpClient.exchange(httpRequest, String.class).blockingFirst().body().toString();
}
There are a number of ways to do it. One is with something like the following:
def json = '{"town":"St. Louis"}'
client.toBlocking().exchange(HttpRequest.POST('/some/uri', json))

JSON API Document de-serializing and serializing using Spine Swift Library

I'm using Spine A Swift library for working with JSON:API
I want to understand how to serialize the data to take full advantage of the JSON API's
I'm using Serializer to achieve this as:
let serializer = Serializer()
serializer.registerResource(MyModel.self)
What i have got ?
let document = try! serializer.deserializeData(data) //data is my response as NSData
I'm able to get the JSON API Document with all the included relationships and data as
document.included
For this I'm casting MyModel to the required data as
MyModel = document.included[0] as! MyModel
As this is not the intended way to fully utilize the JSON :API, any suggestions and what am i missing ?

Save JSON Response as Variable to Deserialise with SwiftyJSON

I'm going to use either SwiftyJSON or EasyFastMapping to deserialise JSON data into variables and constants but I'm not sure on how to save the whole JSON file into its own object, if it is even possible.
I will be using Alamofire to handle the GET request and pull the JSON data down, is it possible to do it like this?
How I want it to work:
1. Alamofire pulls down the JSON data
Alamofire puts the data into an object
SwiftyJSON accesses the downloaded data and allows me to put individual parts of the data into separate variables and constants.
You could take a look at the documentation for SwiftyJSON and Alamofire and you will find plenty of examples.
From Alamofire Readme:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}}
From SwiftJSON Readme:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Your implementation here
}
You can also create a separate response object and deserialize all the response JSON into the object. Also take a look at the built-in JSONSerialization API in the Foundation framework.

Django request Post json

I try to test a view, I receive a json request from the IPad, the format is:
req = {"custom_decks": [
{
"deck_name": "deck_test",
"updates_last_applied": "1406217357",
"created_date": 1406217380,
"slide_section_ids": [
1
],
"deck_id": 1
}
],
"custom_decks_to_delete": []
}
I checked this in jsonlint and it passed.
I post the req via:
response = self.client.post('/library/api/6.0/user/'+ uuid +
'/store_custom_dec/',content_type='application/json', data=req)
The view return "creation_success": false
The problem is the post method in view doesn't find the key custom_decks.
QueryDict: {u'{"custom_decks": [{"deck_id": 1, "slide_section_ids": [1],
"created_date":1406217380, "deck_name": "deck_test"}],
"custom_decks_to_delete": []}': [u'']}>
The problem is the post method in view doesn't find the key custom_decks.
Because it is converting my dict to QueryDict with one key.
I appreciate all helps.
Thanks
You're posting JSON, which is not the same as form-encoded data. You need to get the value of request.body and deserialize it:
data = json.loads(request.body)
custom_decks = data['custom_decks']
As I was having problems with getting JSON data from HttpRequest directly with the code of the other answer:
data = json.loads(request.body)
custom_decks = data['custom_decks']
error:
the JSON object must be str, not 'bytes'
Here is an update of the other answer for Python version >3:
json_str=((request.body).decode('utf-8'))
json_obj=json.loads(json_str)
Regarding decode('utf-8'), as mention in:
RFC 4627:
"JSON text shall be encoded in Unicode. The default encoding is
UTF-8."
I attached the Python link referred to this specific problem for version >3.
http://bugs.python.org/issue10976
python 3.6 and django 2.0 :
post_json = json.loads(request.body)
custom_decks = post_json.get("custom_decks")
json.loads(s, *, encoding=None,...)
Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.
From python 3.6 NO need request.body.decode('utf-8') .
Since HttpRequest has a read() method loading JSON from request is actually as simple as:
def post(self, request, *args, **kwargs):
import json
data = json.load(request)
return JsonResponse(data=data)
If you put this up as a view, you can test it and it'll echo any JSON you send back to you.