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)
}
Related
I want to convert my object into JSON so I implemented following code
import "package:behoove/models/product.dart";
class Order {
Product _product;
int _quantity;
int _id;
Order(this._product, this._quantity, this._id);
int get id => _id;
int get quantity => _quantity;
Product get product => _product;
double get orderPrice => _quantity * double.parse(_product.discountedPrice ?? _product.price);
Map<String, dynamic> toJson() => {
"id": _product.id.toString(),
"name": _product.name,
"price": _product.price,
"quantity": _quantity.toString(),
"attributes": {},
"conditions": []
};
}
JSON from app is
{id: 9, name: GoldStar Classic 032, price: 1200, quantity: 1, attributes: {}, conditions: []}}
Screenshot JSON from app
But JSON from DartPad is
{"id":"1","name":"Sabin","price":200,"quantity":3,"attributes":{},"conditions":[]}
Screenshot JSON from DartPad console
How can I get same output on my app. please help. Also why is it not similar on both DartPad and app?
Instead of calling .toJson() directly use jsonEncode() as in the example (you can run it in DartPad to see difference). Calling jsonEncode(order) will give you a properly formatted json.
import 'dart:convert';
void main() {
final obj = Order();
print(obj.toJson());
print(jsonEncode(obj));
}
class Order {
int id = 0;
int price = 100;
String name = 'asdf';
int quantity = 10;
Map<String, dynamic> toJson() => {
"id": id.toString(),
"name": name,
"price": price,
"quantity": quantity.toString(),
"attributes": {},
"conditions": []
};
}
Output:
// simple toJson that ommits quotation marks
{id: 0, name: asdf, price: 100, quantity: 10, attributes: {}, conditions: []}
// properly encoded json
{"id":"0","name":"asdf","price":100,"quantity":"10","attributes":{},"conditions":[]}
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)
Let be this JSON string:
[
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
]
Let be this class:
export class MyObject{
id: number;
text: string;
}
How can I cast this JSON string to list of MyObject?
If I do:
console.log(<MyObject[]>JSON.parse(json_string));
It returns a list of Object instead of a list of MyObject
You don't necessarily need a class here. You can just use an interface
export interface MyObject{
id: number;
text: string;
}
Then you can just write:
var myObjArray : MyObject[] = [
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
];
If you data comes from the server, you will probably have it in a variable of type any, and you can just assign it to an array of that type and it will work as expected.
var data: any = getFromServer();
var myObjectArray:MyObject[] = data;
In typescript you don't need a class implementing an interface. Any object literal that satisfies the interface contract will do.
If your data is still in string for you can just use JSON.parse(jsonString) to parse the string to JavaScript objects.
See playground here
You will need to create a constructor for your class, and call it for each item in the list you receive.
export class MyObject{
constructor(public id: number, public text: string) { }
}
let data = [
{
"id": 1,
"text": "Jon Doe"
},
{
"id": 1,
"text": "Pablo Escobar"
}
];
let objects = data.map(o => new MyObject(o.id, o.text));
You can check it out in the playground here.
There is a problem when MyObject has 50 or more properties...
Add a constructor in your MyObject class so that it extends your json object.
export class MyObject {
constructor( json: any )
{
$.extend(this, json);
}
id : number;
text : string;
methodOnMyObject() {...}
}
In your ajax callback, create the MyObject object from your json Object:
let newObject = new MyObject( json );
newObject.methodOnMyObject();
I detailed the solution in that post.
One more way to achieve this:
var data: any = getFromServer();
var myObjectArray = data as MyObject;
Or:
var data: any = getFromServer();
var myObjectArray = <MyObject>dataMyObject;
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])
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"
}
]