jdbcTemplate - Convert data from JSON column - mysql

Tools: Spring Booot v2.1.3.RELEASE, MySQL 5.7
I have table with column of type JSON named "properties".
I use jdbcTemplate.queryForList(sql) method to read from this table.
Rest service returns something like this:
[
{
"id": 1,
"name": "users",
"properties": "{\"prop1\": \"value1\"}",
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]
As you can see the "properties" object is type of String.
How to force jdbcTemplete to convert data from JSON column into JSON instead of String?
Expected result:
[
{
"id": 1,
"name": "users",
"properties": {
"prop1": "value1"
},
"description": "smpl descr1",
"log_enabled": false
},
{
"id": 2,
"name": "members",
"properties": null,
"description": "sample description 2",
"log_enabled": true
}
]

I am sorry that JdbcTemplete does not have such function. You have to convert the JSON string to the java object by yourself using your favourite JSON library.
For example , in case of Jackson , you can convert any JSON string to a Map using:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"prop1\": \"value1\" , \"prop2\": 123}";
Map<String,Object> result = mapper.readValue(json,new TypeReference<Map<String,Object>>() {});
result.get("prop1") // "value1"
result.get("prop2") // 123

Related

RealmList<String> as a JSON Schema - Mongo DB Realm

I have a simple model class from which I need to generate the schema on Mongo DB Atlas. But I'm having troubles when it comes to defining RealmList<String> inside a JSON schema. If I insert "array" as a bsonType, I get an error. What should I write instead?
Model class:
class Note : RealmObject {
#PrimaryKey
var _id: ObjectId = ObjectId.create()
var title: String = ""
var description: String = ""
var images: RealmList<String> = realmListOf()
var date: RealmInstant = RealmInstant.from(System.currentTimeMillis(),0)
}
Current Schema:
{
"bsonType": "object",
"properties": {
"_id": {
"bsonType": "objectId"
},
"title": {
"bsonType": "string"
},
"description": {
"bsonType": "string"
},
"images": {
"bsonType": "array"
},
"date": {
"bsonType": "date"
}
},
"required": [
"_id",
"title",
"description",
"images",
"date"
],
"title": "Note"
}
I am not sure which mode you're using but if you're in development mode, when you add an object in the SDK, the server will automatically generate a matching object, as long as the changes are additive, like adding a new object or property
In the queston, the 'images' bson definition looks incomplete
"images": {
"bsonType": "array"
},
While it is an array, it's an array of strings so I believe it should look more like this
"images": {
"bsonType": "array",
"items": {
"bsonType": "string"
}
}
Where the type of items is defined as a string

How do I assign a value in JSON that becomes an enum string value in TypeScript?

I'm trying to add sample data for my unit tests and I'm getting an assignment error when I'm trying to read in the JSON file related to the enum assignment.
types.ts
export enum TestType {
TYPE1 = "type1",
TYPE2 = "type2",
TYPE3 = "type 3"
}
export interface SampleDataType {
id: string;
name: string;
dataType?: TestType;
}
exampleData.json
[
{
"id": "1",
"name": "first",
"dataType": "type1"
},
{
"id": "2",
"name": "second",
"dataType": "type2"
},
{
"id": "3",
"name": "third",
"dataType": "type3"
}
]
unitTest.ts
import * as exampleData from "../../components/__mocks__/test-data/exampleData.json";
//...
const testItems: SampleDataType[] = exampleData;
I'm getting the following error:
I've also tried using "TYPE1" as the sample data value, but no luck. Is there a way to assign the value in json and have it read in the unit test?

SwiftyJSON not working with WebSocket message

I have a socket response that is this:
{"op":0,"d":{"author":{"id":"6699457769390473216","name":"Test","verified":false},"unixTime":1597277057132,"id":"6699465549836976128","group":"64632423765273287342","content":"Yo","_id":"5f34838198980c0023fa49e3"},"t":"MESSAGE"}
and I need to access the "d" object, I've tried doing
print(JSON(data)["d"])
and it just Returns null every time.
If data is of type String, you are probably using the wrong init method to initialize the JSON object. Try using init(parseJSON:) like this:
let jsonString = """
{
"op": 0,
"d": {
"author": {
"id": "6699457769390473216",
"name": "Test",
"verified": false
},
"unixTime": 1597277057132,
"id": "6699465549836976128",
"group": "64632423765273287342",
"content": "Yo",
"_id": "5f34838198980c0023fa49e3"
},
"t": "MESSAGE"
}
"""
let json = JSON(parseJSON: jsonString)
print(json["d"])

How to stream insert JSON array to BigQuery table in Apache Beam

My apache beam application receives a message in JSON array but insert each row to a BigQuery table. How can I support this usecase in ApacheBeam? Can I split each row and insert it to table one by one?
JSON message example:
[
{"id": 1, "name": "post1", "price": 10},
{"id": 2, "name": "post2", "price": 20},
{"id": 3, "name": "post3", "price": 30}
]
BigQuery table schema:
[
{
"mode": "REQUIRED",
"name": "id",
"type": "INT64"
},
{
"mode": "REQUIRED",
"name": "name",
"type": "STRING"
},
{
"mode": "REQUIRED",
"name": "price",
"type": "INT64"
}
]
Here is my solution. I converted JSON string to List once then c.output one by one. My code in in Scala but you can do the same thing in Java.
case class MyTranscationRecord(id: String, name: String, price: Int)
case class MyTranscation(recordList: List[MyTranscationRecord])
class ConvertJSONTextToMyRecord extends DoFn[KafkaRecord[java.lang.Long, String], MyTranscation]() {
private val logger: Logger = LoggerFactory.getLogger(classOf[ConvertJSONTextToMyRecord])
#ProcessElement
def processElement(c: ProcessContext): Unit = {
try {
val mapper: ObjectMapper = new ObjectMapper()
.registerModule(DefaultScalaModule)
val messageText = c.element.getKV.getValue
val transaction: MyRecord = mapper.readValue(messageText, classOf[MyTranscation])
logger.info(s"successfully converted to an EPC transaction = $transaction")
for (record <- transaction.recordList) {
c.output(record)
}
} catch {
case e: Exception =>
val message = e.getLocalizedMessage + e.getStackTrace
logger.error(message)
}
}
}

Parse JSON array in Typescript

i have a JSON response from remote server in this way:
{
"string": [
{
"id": 223,
"name": "String",
"sug": "string",
"description": "string",
"jId": 530,
"pcs": [{
"id": 24723,
"name": "String",
"sug": "string"
}]
}, {
"id": 247944,
"name": "String",
"sug": "string",
"description": "string",
"jlId": 531,
"pcs": [{
"id": 24744,
"name": "String",
"sug": "string"
}]
}
]
}
In order to parse the response, to list out the "name" & "description", i have written this code out:
interface MyObj {
name: string
desc: string
}
let obj: MyObj = JSON.parse(data.toString());
My question is how do i obtain the name and description into a list that can be displayed.
You gave incorrect type to your parsed data. Should be something like this:
interface MyObj {
name: string
description: string
}
let obj: { string: MyObj[] } = JSON.parse(data.toString());
So it's not MyObj, it's object with property string containing array of MyObj. Than you can access this data like this:
console.log(obj.string[0].name, obj.string[0].description);
Instead of using anonymous type, you can also define interface for it:
interface MyRootObj {
string: MyObj[];
}
let obj: MyRootObj = JSON.parse(data.toString());