json serialization of an object - json

I am pretty new in swift and trying to make a http post request using an api with some properties.
I have defined following class
class Order {
var address1 : String?
var address2 : String?
var cellPhone : String?
var city : String?
var countryName : String?
var orderDate : String?
var orderStatus : Int?
var orderedProductList : Array<OrderedProduct>?
var paymentTransactionId : String?
var state : String?
var zip : String?
var countryId : Int?
var orderId : Int?
var orderTotal : Int?
var paymentMethodId : Int?
var userId : Int?
init(address1:String?, address2:String?, cellPhone:String?, city:String?, countryName:String?, orderDate:String?,orderStatus:Int?,orderedProductList:Array<OrderedProduct>?, paymentTransactionId:String?, state:String?, zip:String?, countryId:Int?, orderId:Int?, orderTotal:Int?, paymentMethodId:Int?, userId:Int?)
{
self.address1 = address1
self.address2 = address2
self.cellPhone = cellPhone
self.city = city
self.countryName = countryName
self.countryId = countryId
self.orderDate = orderDate
self.orderStatus = orderStatus
self.paymentTransactionId = paymentTransactionId
self.state = state
self.zip = zip
self.orderId = orderId
self.orderTotal = orderTotal
self.paymentMethodId = paymentMethodId
self.userId = userId
self.orderedProductList = orderedProductList
}
}
Order Instance is:
var totalOrderInfo = Order(address1: address, address2: apartment, cellPhone: phone, city: city, countryName: cName, orderDate: "\(year)-\(month)-\(day)T\(hour):\(minutes):\(seconds)", orderStatus: 1, orderedProductList: orderedProductList, paymentTransactionId: transctionID, state: state, zip: zip, countryId: cId, orderId: 0, orderTotal: returnValue1, paymentMethodId: 1, userId: userID)
The JSON representation of totalOrderInfo would be the following:
{"address1":"Mirpur","address2":"D6, f8","cellPhone":"01852540565","city":"fghff","countryName":"Bangladesh","orderDate":"2017-02-25T11:28:24","orderStatus":1,"orderedProductList":[{"discount":0.0,"orderDetailId":0,"price":30000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":5,"productViews":0},{"discount":0.0,"orderDetailId":0,"price":50000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":8,"productViews":0},{"discount":0.0,"orderDetailId":0,"price":2000.0,"quantity":1,"shippingCharge":50.0,"supplierId":0,"tax":0.0,"type":{"isBook":false,"typeId":0},"productId":9,"productViews":0}],"paymentTransactionId":"1215455638874521","state":"fyy","zip":"4525","countryId":23,"orderId":0,"orderTotal":82000.0,"paymentMethodId":1,"userId":0}
How can I serialize the totalOrderInfo instance and get the above JSON??
Thanks

You could use a library, such as: Object Mapper
In your case your class Order would be like this:
class Order: Mappable {
var address1 : String?
var address2 : String?
var cellPhone : String?
var city : String?
var countryName : String?
var orderDate : String?
var orderStatus : Int?
var orderedProductList : Array<OrderedProduct>?
var paymentTransactionId : String?
var state : String?
var zip : String?
var countryId : Int?
var orderId : Int?
var orderTotal : Int?
var paymentMethodId : Int?
var userId : Int?
init?(map: Map){
}
init(address1:String?, address2:String?, cellPhone:String?, city:String?, countryName:String?, orderDate:String?,orderStatus:Int?,orderedProductList:Array<OrderedProduct>?, paymentTransactionId:String?, state:String?, zip:String?, countryId:Int?, orderId:Int?, orderTotal:Int?, paymentMethodId:Int?, userId:Int?)
{
self.address1 = address1
self.address2 = address2
self.cellPhone = cellPhone
self.city = city
self.countryName = countryName
self.countryId = countryId
self.orderDate = orderDate
self.orderStatus = orderStatus
self.paymentTransactionId = paymentTransactionId
self.state = state
self.zip = zip
self.orderId = orderId
self.orderTotal = orderTotal
self.paymentMethodId = paymentMethodId
self.userId = userId
self.orderedProductList = orderedProductList
}
mutating func mapping(map: Map){
address1 <- map["address1"]
address2 <- map["address2"]
cellPhone <- map["cellPhone"]
city <- map["city"]
countryName <- map["countryName"]
countryId <- map["countryId"]
orderDate <- map["orderDate"]
orderStatus <- map["orderStatus"]
paymentTransactionId <- map["paymentTransactionId"]
state <- map["state"]
zip <- map["zip"]
orderId <- map["orderId"]
orderTotal <- map["orderTotal"]
paymentMethodId <- map["paymentMethodId"]
userId <- map["userId"]
orderedProductList <- map["orderedProductList"]
}
}
As you also have an Array<OrderedProduct> in your code, you will have to do the same to the OrderedProduct class.
After that, you can convert the model object to a JSON string using:
let order = Order(address1, address2.......)
let jsonString = order.toJSONString(prettyPrint: true)
If you want to know more about the library and how to install it, you can check the official documentation at their Github Project page

By the serialization of JSON data you will get dictionary, so add new initialization method from dictionary in your Order class as follows:
class Order {
.
.
.
.
init(dictionary: [String: AnyObject]) {
super.init()
address1 = dictionary["address1"] as? String
address2 = dictionary["address2"] as? String
// and so on
}
Then where you load your JSON data you init your object from JSON dictionary:
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
let order = Order(dictionary: json)
} catch let error as NSError {
print(error)
}
(where data is the received data from API)

Related

Making JSON string to Kotlin object not working

I am trying to send a multipart/formdata object to the backend that contains a Freelancer object and two image files that have to be stored on the server. The saving on disc part works, but saving the JSON string as a freelancer object is not working. I tried converting the string with Jackson objectmapper but I think I am doing something wrong. When I debug the application it crashes at mapper.readValue and goes straight to the catch().
I also tried to work with kotlinx.serializer, but the import just would not work so I switched to Jackson.
The Kotlin controller that takes in the request:
private val imageDirectory = System.getProperty("user.dir") + "/images/"
#PostMapping(consumes = ["multipart/form-data"])
fun saveUser(
#RequestParam("profileImage") profileImage: MultipartFile,
#RequestParam("fileIdImage") fileIdImage: MultipartFile,
#RequestParam("freelancer") freelancer: String,
): ResponseEntity<*> {
return try {
val mapper = ObjectMapper();
val freelancerJson: Freelancer = mapper.readValue(freelancer, Freelancer::class.java)
println(freelancerJson.aboutYou)
makeDirectoryIfNotExist(imageDirectory)
val profileImagePath: Path = Paths.get(imageDirectory, profileImage.originalFilename)
val idImagePath: Path = Paths.get(imageDirectory, fileIdImage.originalFilename)
Files.write(profileImagePath, profileImage.bytes);
Files.write(idImagePath, fileIdImage.bytes);
JsonResponse(HttpStatus.OK, "Saved freelancer} ").createResponseEntity()
} catch (e: Exception) {
JsonResponse(HttpStatus.INTERNAL_SERVER_ERROR, e.message.toString()).createResponseEntity()
}
}
The request from the front end using vue:
The console output of the formdata:
Freelancer model:
#Entity
data class Freelancer(
#Id
val id: Int,
//maps ID to freelancer primary key
#MapsId
#OneToOne(targetEntity = User::class)
#JoinColumn(name = "freelancer_id")
//ignores the freelancer id because it is already mapped to val id
#JsonIgnore
val freelancerId: User,
val firstName: String? = null,
val lastName: String? = null,
val dateOfBirth: Date? = null,
val kvk: String? = null,
val btw: String? = null,
val phone: String? = null,
val street: String? = null,
val zipcode: String? = null,
val city: String? = null,
val housenumber: Int? = 0,
val addition: String? = null,
val nameCardHolder: String? = null,
val iban: String? = null,
val referral: String? = null,
val specialism: String? = null,
val aboutYou: String? = null,
val motivation: String? = null,
val workExperience: Int? = null,
val driverLicense: Boolean? = null,
val ownTransport: Boolean? = null,
val identificationImage: String? = null,
val smallBusinessScheme: Boolean? = false,
val profileImage: String? = null,
val previousWorkedPlatform: String? = null,
val servicesAmount: Int? = null,
val previousWorkedRating: Int? = null,
val foundBy: String? = null,
val privacyStatement: Boolean? = null,
)
I solved it by adding ID to the Json object I was sending to the backend, because my model has a one-to-one relation with another model I had to include it when mapping the Json to the model.

sqlx missing destination name with MySQL

I have a query which returns result of mysql json_object function. But when I try to call my api I got an error
missing destination name json_object('id', vd.id, 'title', vd.title...
type Vacancies struct {
ID int `json:"id"`
Title string `json:"title"`
Logo string `json:"logo"`
Items []string `json:"items"`
}
func (r *repository) GetVacancies(ctx context.Context) []*Vacancies {
const queryString = "select json_object('id', vd.id, 'title', vd.title, 'logo', vd.logo, 'items', json_array((select GROUP_CONCAT(json_object('id', id, 'title', title, 'description', description)) from vacancies as v where department_id = vd.id order by vd.sort))) from vacancy_departments as vd order by vd.sort"
defer utils.StartRelicDatastoreSegment(
ctx, newrelic.DatastoreMySQL, "Vacancies.GetVacancies", "Select", queryString,
).End()
var result []*Vacancies
if err := mysql.Client().Slave().Select(&result, queryString); err != nil {
logger.Get().Error("err while getting vacancies", zap.Error(err))
return nil
}
return result
}
How is it possible to get valid data for golang structure?

how can i parse json weather response

this is my response from weather map api
{
"message": "accurate",
"cod": "200",
"count": 3,
"list": [
{
"id": 2641549,
"name": "Newtonhill",
"coord": {
"lat": 57.0333,
"lon": -2.15
},
"main": {
"temp": 275.15,
"pressure": 1010,
"humidity": 93,
"temp_min": 275.15,
"temp_max": 275.15
},
"dt": 1521204600,
"wind": {
"speed": 9.3,
"deg": 120,
"gust": 18
},
"sys": {
"country": ""
},
"rain": null,
"snow": null,
"clouds": {
"all": 75
},
"weather": [
{
"id": 311,
"main": "Drizzle",
"description": "rain and drizzle",
"icon": "09d"
}
]
}
how can i get the description i did get the temperature using a retrofit by seriazable object but i could'nt get the weather description
i did that to get temperature and the country
class WeatherResponse {
#SerializedName("sys")
var sys: Sys? = null
#SerializedName("main")
var main: Main? = null
#SerializedName("weather")
var weather: Weather? = null
}
class Main {
#SerializedName("temp")
var temp: Float = 0.0f
}
and i my main class im using a callback
fun getCurrentData() {
val retrofit = Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(WeatherService::class.java)
val call = service.getCurrentWeatherData(lat, lon, AppId)
call.enqueue(object : Callback<WeatherResponse> {
override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
if (response.code() == 200) {
val weatherResponse = response.body()!!
var temp = (weatherResponse.main!!.temp - 273).toString().substring(0,3) + " ÂșC"
tmp.text=temp
}
}
override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
}
})
}
Here is POJO class for your JSON. It now can be parsed easily.
WeatherResponse.kt
data class WeatherResponse(
#SerializedName("cod")
val cod: String? = null,
#SerializedName("count")
val count: Int? = null,
#SerializedName("list")
val list: List<X?>? = null,
#SerializedName("message")
val message: String? = null
) {
data class X(
#SerializedName("clouds")
val clouds: Clouds? = null,
#SerializedName("coord")
val coord: Coord? = null,
#SerializedName("dt")
val dt: Int? = null,
#SerializedName("id")
val id: Int? = null,
#SerializedName("main")
val main: Main? = null,
#SerializedName("name")
val name: String? = null,
#SerializedName("rain")
val rain: Any? = null,
#SerializedName("snow")
val snow: Any? = null,
#SerializedName("sys")
val sys: Sys? = null,
#SerializedName("weather")
val weather: List<Weather?>? = null,
#SerializedName("wind")
val wind: Wind? = null
)
data class Clouds(
#SerializedName("all")
val all: Int?
)
data class Coord(
#SerializedName("lat")
val lat: Double? = null,
#SerializedName("lon")
val lon: Double? = null
)
data class Main(
#SerializedName("humidity")
val humidity: Int? = null,
#SerializedName("pressure")
val pressure: Int? = null,
#SerializedName("temp")
val temp: Double? = null,
#SerializedName("temp_max")
val tempMax: Double? = null,
#SerializedName("temp_min")
val tempMin: Double? = null
)
data class Sys(
#SerializedName("country")
val country: String?
)
data class Weather(
#SerializedName("description")
val description: String? = null,
#SerializedName("icon")
val icon: String? = null,
#SerializedName("id")
val id: Int? = null,
#SerializedName("main")
val main: String? = null
)
data class Wind(
#SerializedName("deg")
val deg: Int? = null,
#SerializedName("gust")
val gust: Int? = null,
#SerializedName("speed")
val speed: Double? = null
)
}
You can get Weather description by using
var description = weatherResponse.list?.get(0)?.weather?.get(0)?.description

Contenent is not showing under auto complete text box

I am implementing auto-compete textbox using MVC 4. According to the requirement the textbox can take multiple names(here EmployeeName) separated by "," (comma). I have written the following code for the controller:
public JsonResult EmployeeList(string strEmpName)
{
List<string> list = strEmpName.Split(',').ToList();
list = list.Select(s => s.Trim()).ToList();
//Extract the term to be searched from the list
string searchTerm = list.LastOrDefault().ToString().Trim();
//Return if Search Term is empty
if (string.IsNullOrEmpty(searchTerm))
{
//return new string[0];
}
List<string> excludeEmployeeName = new List<string>();
if (list.Count > 1)
{
list.RemoveAt(list.Count - 1);
excludeEmployeeName = list;
}
var query = (EmployeeDAL.GetEmployee().Where(x => x.EmployeeName.StartsWith(searchTerm.ToString().ToUpper()))).ToList();
var myList = new List<string>();
foreach (var emp in query.ToList())
{
myList.Add(emp.EmployeeName.ToString());
}
return Json(myList, JsonRequestBehavior.AllowGet);
}
The above function is returning JSON.
Data is like:
public class EmployeeDAL
{
public static List<Employee> GetEmployee()
{
var empList = new List<Employee>
{
new Employee { EmployeeId = "E001", EmployeeName = "Alex", DepartmentId = 1 },
new Employee { EmployeeId = "E002", EmployeeName = "Alan", DepartmentId = 2 },
new Employee { EmployeeId = "E003", EmployeeName = "Johny", DepartmentId = 3 },
new Employee { EmployeeId = "E004", EmployeeName = "Joe", DepartmentId = 1 },
new Employee { EmployeeId = "E005", EmployeeName = "Thomas", DepartmentId = 3 },
new Employee { EmployeeId = "E006", EmployeeName = "Sarah", DepartmentId = 3 },
new Employee { EmployeeId = "E007", EmployeeName = "Rahul", DepartmentId = 4 },
new Employee { EmployeeId = "E008", EmployeeName = "Raman", DepartmentId = 1 },
new Employee { EmployeeId = "E009", EmployeeName = "Mandy", DepartmentId = 2 },
new Employee { EmployeeId = "E010", EmployeeName = "Rohit", DepartmentId = 4 },
new Employee { EmployeeId = "E011", EmployeeName = "Sanjay", DepartmentId = 1 },
new Employee { EmployeeId = "E012", EmployeeName = "Abhi", DepartmentId = 3 },
new Employee { EmployeeId = "E013", EmployeeName = "Martin", DepartmentId = 1 },
new Employee { EmployeeId = "E014", EmployeeName = "Robin", DepartmentId = 2 },
new Employee { EmployeeId = "E015", EmployeeName = "Rohit", DepartmentId = 1 },
new Employee { EmployeeId = "E016", EmployeeName = "William", DepartmentId = 3 },
new Employee { EmployeeId = "E017", EmployeeName = "Sourav", DepartmentId = 2 },
new Employee { EmployeeId = "E018", EmployeeName = "Alex", DepartmentId = 2 },
};
return empList.ToList();
}
}
In view I have written the following script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtEmployeeName").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Employee/EmployeeList",
data: "{'strEmpName':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert(result.responseText);
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtEmployeeName").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
When I run the application and debug the json script using firebug, I can see the data is coming rightly according the letter I type in the text box (txtEmployeeName) but is not showing in the browser window. I have given the total script so that any one can run it.
Any help will be thankfully accepted.

List of string in a record to CSV?

How does one write a list of string in a record to CSV without the lists being truncated?
CSV Writer:
let toSepFile sep header (fileName:string) (s:'record seq)=
let schemaType=typeof<'record>
let fields = Reflection.FSharpType.GetRecordFields(schemaType)
let toStr fields =
fields
|> Seq.fold(fun res field-> res+field+sep) ""
use w = new System.IO.StreamWriter(fileName)
if header then
let header_str= fields
|> Seq.map(fun field -> field.Name)
|> toStr
w.WriteLine(header_str)
let elemToStr (elem:'record) =
//for each field get value
fields
|> Seq.map(fun field -> string (FSharpValue.GetRecordField(elem,field)))
|> toStr
s
|>Seq.map(elemToStr)
|>Seq.iter(fun elem -> w.WriteLine(elem))
Test Data (Deedle test set):
let peopleRecds =
[ { Name = "Joe"; Age = 51; Countries = [ "UK"; "US"; "UK"] }
{ Name = "Tomas"; Age = 28; Countries = [ "CZ"; "UK"; "US"; "CZ" ] }
{ Name = "Suzanne"; Age = 15; Countries = [ "US" ] } ]
Current CSV Output:
Name Age Countries
"Joe 51 [CZ; UK; US; ... ] "
"Tomas 28 [CZ; UK; US; ... ] "
"Suzanne 15 [US] "
So is it possible see the full list of strings from the CSV output, instead of the "..."?
Edit: Desired output:
Name Age Countries
"Joe 51 [CZ; UK; US] "
"Tomas 28 [CZ; UK; US; CZ] "
"Suzanne 15 [US] "
The trouble you're having is that for Lists, the ToString() method truncates the output. The workaround is to not use ToString(), but instead use sprint "%A" *list here*.