How to write a kotlin data class to match json? - json

I am using Retrofit to call API and using converter-gson to convert response json to kotlin
This is response
{
"id": "1",
"rank": "1",
"name": "Challenge",
"status": "E",
"createDate": "2018-09-17 15:01:28",
"lastModDate": "2018-09-17 15:06:32",
"category": "DINING",
"photo": {
"path": "http://example.com/xxx.jpg",
"size": [
400,
267
]
}
}
And this is data class.
data class ServiceList (val id:Int,
val rank:Int,
val name:String,
val status:String,
val lastModDate:String,
val category:String,
???????)
How to complete this class?

You can declare another data class to describe the photo property like so:
data class ServiceList(val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: Photo) {
data class Photo(val size: List<Int>, val path: String)
}
If the Photo is to be used in other contexts as well you can pull it out to be a top level class:
data class ServiceList (val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: ServiceListPhoto)
data class ServiceListPhoto(val size: List<Int>, val path: String)

Related

GraphQL to JSON parsing?

Hi I am trying to format my graphql query to json request like this. I want to pass id as string with value "3", RN when I am sending this as a json request , graphql denies with error. How do I resolve this ?
{"query":"{user(id:3){id,firstName,age}}"} {
"errors": [
{
"message": "String cannot represent a non string value: 3",
"locations": [
{
"line": 1,
"column": 10
}
]
}
]
}
Added schema in edit1:
`# Exposes a URL that specifies the behavior of this scalar.
directive #specifiedBy(
The URL that specifies the behavior of this scalar.
url: String!
) on
| SCALAR
schema {
query: RootQueryType
mutation: Mutation
}
type Company {
id: String
name: String
description: String
users: [User]
}
type Mutation {
addUser(firstName: String!, lastName: String, age: Int!, socialSecurity: String, companyId: String): User
deleteUser(id: String!, companyId: String): User
editUser(id: String!, firstName: String, lastName: String, age: Int, socialSecurity: String, companyId: String): User
addCompanies(name: String!, description: String): Company
editCompanies(id: String!, name: String, description: String): Company
}
type RootQueryType {
user(id: String): User
company(id: String): Company
}
type User {
id: String
firstName: String
lastName: String
age: Int
socialSecurity: String
company: Company
}
`
Without having the schema it is a bit hard to be sure, but it seems like you need to change the type of the input id of the user field from String to ID. The scalar ID type does accept strings and numbers as input.

GSON not Parsing Nested JSON Object to a value

Hello I am using GSON to parse a route object, which contains the following JSON:
{
"mapOverlays": [
{
"id": 1,
"route": 73,
"url": "https://en.wikiarquitectura.com/wp-content/uploads//2017/01/White_House_distr_2C2BA.png",
"lat": 0.00,
"lng": 0.00,
"width": 2000,
"height": 1335,
"scale": 1,
"constraints": {
"w": [
0.00,
0.00
],
"x": [
0.00,
0.00
],
"y": [
0.00,
0.00
]
},
"flags": ""
}
]
}
The issue is when I try to access the JsonObject of constraints, I get an empty JSONObject.
Here is the Data model class of the Basemaps.
import com.google.gson.JsonObject
import com.travelstorysgps.travelstoryssdk.extensions.md5
import java.io.Serializable
class Basemap (
val id: Int,
val route: Int,
val url: String,
val lat: Double,
val lng: Double,
val width: Int,
val height: Int,
val scale: Double,
val constraints : JsonObject ,
val flags: String
) : Serializable {
val filename: String
get() = url.md5() + ".file"
}
And this is the output I get when I call Basemap.constraints : I/System.out: [BASEMAP]: {} It should contain JSONArrays named w,x, and y.
Is there something wrong with my Data model class?
EDIT: Here is the parent Route object:
package com.travelstorysgps.travelstoryssdk.data.model
import android.content.Context
import com.travelstorysgps.travelstoryssdk.data.Location
import java.io.Serializable
import java.util.*
import kotlin.math.floor
data class Route(
val route: RouteDefinition,
val tracks: List<Track>,
val geotags: List<Geotag>,
val images: List<Image>,
val music: List<Music>,
val assets: AssetList,
val orgs: List<Organization>,
val mapOverlays: List<Basemap>,
val ecoupons: List<Coupon>,
var distance: Int,
var routeKey: String = "",
var isDownloading: Boolean = false
) : Serializable {
val artists: List<Int>
get() = music.map { it.artist }.distinct()
}```
The Basemap object is wrapped in parent JSON object under mapOverlays array field. You need an additional class to deserialize in proper structure.
data class Parent(val mapOverlays: List<Basemap>)
fun someFn(json: String) {
val parent = Gson().fromJson(json, Parent::class.java)
println(parent.mapOverlays[0].constraints)
}

How can I parse this JSON to a record type?

I have some data I'll be fetching at runtime:
/* {id: 1, name: 'brad', age: 27, address: { city: 'city1', state: 'state1' } } */
let data = "{\"id\":1,\"name\":\"brad\",\"age\":27,\"address\":{\"city\":\"city1\",\"state\":\"state1\"}}";
Using ReasonML and BuckleScript, how can I can get this data in the form:
type address = {
city: string,
state: string
};
type person = {
id: int,
name: string,
age: option int,
address: option address
};
The solution I've come up with are 100s of lines long.
Using bs-json:
let parseAddress json =>
Json.Decode.{
city: json |> field "city" string,
state: json |> field "state" string
};
let parsePerson json =>
Json.Decode.{
id: json |> field "id" int,
name: json |> field "name" string,
age: json |> optional (field "age" int),
address: json |> optional (field "address" parseAddress)
};

How to convert Scala JsArray to custorm object

I'm new to Scala and don't see a way to do this.
I have this class:
case class User(userId: Int, userName: String, email: String, password:
String) {
def this() = this(0, "", "", "")
}
case class Team(teamId: Int, teamName: String, teamOwner: Int,
teamMembers: List[User]) {
def this() = this(0, "", 0, Nil)
}
I'm sending post request as :-
'{
"teamId" : 9,
"teamName" : "team name",
"teamOwner" : 2,
"teamMembers" : [ {
"userId" : 1000,
"userName" : "I am new member",
"email" : "eamil",
"password" : "password"
}]
}'
I get request:-
I tried:-
val data = (request.body \ "teamMembers")
val data2 = (request.body \ "teamId")
val data3 = (request.body \ "teamName")
data: [{"userId":1000,"userName":"I am new
member","email":"eamil","password":"password"}]
data2: 9
data3: "team name"
How to convert data to User object?
[{"userId":1000,"userName":"I am new
member","email":"email","password":"password"}]
As an option, you can read Users like this
import play.api.libs.json.{JsArray, Json}
case class User(
userId: Int,
userName: String,
email: String,
password: String) {
}
case class Team(
teamId: Int,
teamName: String,
teamOwner: Int,
teamMembers: List[User]) {
}
implicit val userFormat = Json.format[User]
implicit val teamFormat = Json.format[Team]
val jsonStr = """{
"teamId" : 9,
"teamName" : "team name",
"teamOwner" : 2,
"teamMembers" : [ {
"userId" : 1000,
"userName" : "I am new member",
"email" : "eamil",
"password" : "password"
}]
}"""
val json = Json.parse(jsonStr)
// Team(9,team name,2,List(User(1000,I am new member,eamil,password)))
json.as[Team]
// Seq[User] = ListBuffer(User(1000,I am new member,eamil,password))
val users = (json \ "teamMembers").as[JsArray].value.map(_.as[User])

How to convert Squeryl query object to JSON - Play Framework

Case
This case are using Scala, Play Framework, Jerkson and Squeryl. I'm trying to convert the query resultset to JSON but the result presents just the 'persisted' field.
Question
Why the Json.generate() is not printing all entity fields?
Controller
package controllers.api
import play.api.mvc._
import play.Logger
import play.api.data.Form
import play.api.data.Forms.{mapping, text, optional}
import com.codahale.jerkson.Json
import org.squeryl.PrimitiveTypeMode._
import models.{ApplicationDatabase, Category}
object Categories extends Controller {
def findAll = Action {
val json = inTransaction {
val list = from(ApplicationDatabase.categories)(categories =>
select(categories)
orderBy(categories.title)
)
Logger.info(list.toString)
Json.generate(list)
}
Ok(json).as(JSON)
}
def findById(id: Long) = Action {
val category = inTransaction {
ApplicationDatabase.categories.lookup(id)
}
Ok(Json.generate(category)).as(JSON)
}
}
Category Entity
package models
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.annotations.Column
class Category(var uid: String, var title: String) extends FlashcardsDbObject {
}
Base Entity
package models;
import java.sql.Timestamp
import org.squeryl._
import org.squeryl.annotations.{Column}
import org.squeryl.PrimitiveTypeMode._
class FlashcardsDbObject extends KeyedEntity[Long] {
val id: Long = 0
#Column("created_at")
var createdAt = new Timestamp(System.currentTimeMillis)
#Column("updated_at")
var updatedAt = new Timestamp(System.currentTimeMillis)
}
Problem
Result
{
persisted: true
},
{
persisted: true
},
Expected
{
id: 1,
uid: 'chemistry',
title: 'Chemistry'
persisted: true
},
{
id: 2,
uid: 'biology',
title: 'Biology'
persisted: true
},
Probably this is not the best solution but when I imported and declared JsonProperty into the field worked for me:
package models
import org.squeryl.KeyedEntity
import org.squeryl.annotations._
import org.squeryl.PrimitiveTypeMode._
import org.codehaus.jackson.annotate.JsonProperty
case class Category(val id: Int = 0,
#JsonProperty("uid")
val uid: String,
#JsonProperty("title")
val title: String) extends KeyedEntity[Int] {
}
Result
[
{
id: 3,
uid: "biology",
title: "Biology"
},
{
id: 1,
uid: "general-chemistry",
title: "General Chemistry"
},
{
id: 4,
uid: "organic-chemistry",
title: "Organic Chemistry"
},
{
id: 2,
uid: "physics",
title: "Physics"
}
]