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.
I am implementing json API using Django Rest Framework.
Since sqlite is being used for database, json data is stored as string and when the data is requested, serializer parse the string and convert into json and sent to client side. This implementation worked for simple json file as shown in left picture. However, this cannot work for nested json as shown right picture.
Can anyone tell me how I should revise serializer in order to work for nested json also?
serializer.py
class strToJson(serializers.CharField):
def to_representation(self,value):
x=JSON.loads(value)
return x
class summarySerializer(serializers.ModelSerializer):
project=serializers.CharField(read_only=True,source="html.project")
version = serializers.CharField(read_only=True, source="html.version")
id = serializers.IntegerField(read_only=True, source="html.pk")
json = strToJson()
class Meta:
model=summary
fields=('id','project','version','json')
model.py
class summary(models.Model):
html = models.ForeignKey(html, on_delete=models.CASCADE,related_name='summaries')
keyword = models.CharField(max_length=50, default='test')
json = models.TextField(default='test')
I am using Play Framework and I am trying to convert a Scala object to a JSON string.
Here is my code where I get my object:
val profile: Future[List[Profile]] = profiledao.getprofile(profileId);
The object is now in the profile value.
Now I want to convert that profile object which is a Future[List[Profile]] to JSON data and then convert that data into a JSON string then write into a file.
Here is the code that I wrote so far:
val jsondata = Json.toJson(profile)
Jackson.toJsonString(jsondata)
This is how I am trying to convert into JSON data but it is giving me the following output:
{"empty":false,"traversableAgain":true}
I am using the Jackson library to do the conversion.
Can someone help me with this ?
Why bother with Jackson? If you're using Play, you have play-json available to you, which uses Jackson under the hood FWIW:
First, you need an implicit Reads to let play-json know how to serialize Profile. If Profile is a case class, you can do this:
import play.api.libs.json._
implicit val profileFormat = Json.format[Profile]
If not, define your own Reads like this.
Then since getprofile (which should follow convention and be getProfile) returns Future[List[Profile]], you can do this to get a JsValue:
val profilesJson = profiledao.getprofile(profileId).map(toJson)
(profiledao should also be profileDao.)
In the end, you can wrap this in a Result like Ok and return that from your controller.
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.
I'm learning Swift lang and one of the things that would be great to hear others input about is "How you handle models from JSON responses"? For example -
I have User.swift model:
class User: NSObject {
var user_token:String?
var email:String?
}
and also I would like to use KeyValueObjectMapping as I do in Obj-C projects. Unfortunately this doesn't work here:
let parser = DCKeyValueObjectMapping.mapperForClass(User)
let user = parser.parseDictionary(data.objectForKey("user") as NSDictionary) as User
println(user.user_token) // returns nil
How do you create your models in Swift?
I recommend using code generation to generate models in Swift based on JSON. To that end, I've created a tool at http://www.guideluxe.com/JsonToSwift to make modeling and parsing JSON as easy as possible.
After you've submited a sample JSON object with a class name to the tool, it will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.
After copying the generated code into your project as a Swift class(es), you only need to supply an NSData object containing JSON that matches the sample provided to the tool.
Other than Foundation, there are no dependencies.
Here's how to create an NSData object from a JSON file to test with.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
I would suggest using SwiftyJSONModel there your model would look something like:
import SwiftyJSONModel
class User: NSObject, JSONObjectInitializable {
enum PropertyKey : String {
case user_token, email
}
var user_token:String?
var email:String?
required init(object: JSONObject<PropertyKey>) throws {
user_token = object.value(for: .user_token)
email = object.value(for: .email)
}
}
This library has 3 nice things:
You don't have to explicitly cast to String as library will infer the type
You can have non-optional properties and library will tell you which exact field was wrong
All the keys to the model are incapsulated in enum which gives you auto-complition when you type the keys and guarantees that you cannot access keys, that are not in enum
I'm using jsoncafe easiest and customizable template base model class generator with different framwroks like SwiftyJSON, Codable, Gloss, Simple Swift Class even you can make your own template
jsoncafe.com
Here is some example code for Model Class and parsing JSON response with out any library.
Model Class
class User: NSObject{
var user_token: String = ""
var email: String = ""
}
Example code to call web-service api and Parsing.
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
//println("Result : \(jsonResult)")
let model = User()
model. user_token = jsonResult["user_token"] as NSString
model. email = jsonResult["email"] as NSString
})
If you want a more rigorous approach and have access to JSON schemas as meta description for your JSON documents, I wrote a code generator which can handle those (JSON schema, draft 4):
https://github.com/werner77/MappableObjectGenerator
My tools supports basically any programming language, because it is based on code generation templates, but is focussed on ObjectiveC and Swift 4 support right now.
May be its too late.
You can also try using the link
http://www.json4swift.com/results.php
Where in you just need to paste the JSON values and it gives you the swift files instead.