Can I display JSON Data with an SQL Query? - javascript

Can I display JSON Data with an SQL Query?
The segment below is my current JSON data:
[
{
"id":"BKU0000007",
"judul":"jsjsj",
"no_isbn":"ssksk",
"penulis":"jsjsj",
"penerbit":"iieie",
"tahun_terbit":"2011",
"halaman":"202",
"berat":"220",
"cover":"20202",
"dimensi":"0202",
"kategori":"Horor",
"bahasa":"2020",
"stok":"22020",
"gambar":"BKU0000007.jpeg",
"harga":"333",
"sinopsis":"0202022"
},
{
"id":"BKU0000006",
"judul":"sshhs",
"no_isbn":"3i3i3i",
"penulis":"ssiis",
"penerbit":"oo3o3",
"tahun_terbit":"2009",
"halaman":"20",
"berat":"10000",
"cover":"alks",
"dimensi":"20x30",
"kategori":"",
"bahasa":"skks",
"stok":"20",
"gambar":"BKU0000006.jpeg",
"harga":"29999",
"sinopsis":"skkssk"
}
]
[
{
"id":"BKU0000007",
"judul":"jsjsj",
"no_isbn":"ssksk",
"penulis":"jsjsj",
"penerbit":"iieie",
"tahun_terbit":"2011",
"halaman":"202",
"berat":"220",
"cover":"20202",
"dimensi":"0202",
"kategori":"Horor",
"bahasa":"2020",
"stok":"22020",
"gambar":"BKU0000007.jpeg",
"harga":"333",
"sinopsis":"0202022"
},
{
"id":"BKU0000006",
"judul":"sshhs",
"no_isbn":"3i3i3i",
"penulis":"ssiis",
"penerbit":"oo3o3",
"tahun_terbit":"2009",
"halaman":"20",
"berat":"10000",
"cover":"alks",
"dimensi":"20x30",
"kategori":"",
"bahasa":"skks",
"stok":"20",
"gambar":"BKU0000006.jpeg",
"harga":"29999",
"sinopsis":"skkssk"
}
]
I would like to generate this data using an SQL query such as:
SELECT * FROM data etc...
How can I accomplish this task? Can someone please guide me through this?
Thank you for your time and patience in resolving this matter.

I can suggest something like below:
a) you need to use ObjectMapper object
b) call writeValueAsString(object) of ObjectMapper object
c) To use ObjectMapper you need to have jackson core, jackson annotation,jackson databind jar in your classpath
Sample example:
I create Example class to simulate your solution-code is as below:
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
class Example{
int id;
String name;
public Example(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainApp {
public static void main(String[] args) throws JsonProcessingException {
List<List<Example>> list=new ArrayList<List<Example>>();
List<Example> exampleList1=new ArrayList<>();
exampleList1.add(new Example(1,"A"));
list.add(exampleList1);
List<Example> exampleList2=new ArrayList<>();
exampleList2.add(new Example(1,"B"));
list.add(exampleList2);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String writeValueAsString = mapper.writeValueAsString(list);
System.out.println(writeValueAsString);
}
}
Output:
[[{"id":1,"name":"A"}],[{"id":1,"name":"B"}]]
You replace your properties with Example class.
(If you have dao code then you need to prepare list of list of example object from dao layer after calling sql query and get result)
Hope you got the idea!!

Related

How to change the property of a specific object when buttonclick occurs, using a PUT-method (JSON) in react and springboot

I have made some code inside of the spring boot back-end application which allows me to change a property of a specific object, this property which needs to be changed is the "status" property:
#Entity
public class Pakketje {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int code;
private String status = "In magazijn";
public Pakketje() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
To change the property of that object, i will need to state the ID of that object (i think) inside of the react frontend application, and then fetch the PUT-method.
I will show you the method to change the property inside of my spring boot back-end application, this method can be found in the 'Service' class. 'bestaandPakketje' means existing pakketje.
#Override
public Pakketje getPakketjeById(int id) {
return pakketjeRepository.findById(id).orElse(null);
}
#Override
public Pakketje statusOnderweg(Pakketje pakketje) {
Pakketje bestaandPakketje = pakketjeRepository.findById(pakketje.getId()).orElse(null);
bestaandPakketje.setStatus(pakketje.getStatus());
return pakketjeRepository.save(bestaandPakketje);
}
}
And here is the controller:
public class PakketjeController {
#SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
#Autowired
private PakketjeService pakketjeService;
#PostMapping("/add")
public String add(#RequestBody Pakketje pakketje) {
pakketjeService.pakketjeOpslaan(pakketje);
return "Pakketje opgeslagen!";
}
#GetMapping("/getAll")
public List<Pakketje> getAllePakketjes(){
return pakketjeService.getAllePakketjes();
}
#GetMapping("/getById/{id}")
public Pakketje findPakketjeById(int id) {
return pakketjeService.getPakketjeById(id);
}
#PutMapping("/updateOnderweg")
public Pakketje statusIsOnderweg(#RequestBody Pakketje pakketje) {
return pakketjeService.statusOnderweg(pakketje);
}
}
Now the next step is verry hard for me. Each 'pakketje' has his own button which can be clicked to change the property (I will upload the picture so please check it). When that button is clicked the property automatically should change from "In magazijn "to "onderweg".
I would appreciate some help!

Access methods from .jar file in react native(android)

I'd like to import a module written natively (java, Android) into my React Native sources, in JS.
To access your functionality implemented in java you have to create a bridge. You can see the most recent instructions in the RN documentation site*.
The steps, assuming React Native 0.61, for a hello world, to be implemented in the android project inside the react native app directory (android directory):
1) First you create a simple POJO class to be returned to the react native context:
class MyData{
private int timeSpentSleeping;
public int getTimeSpentSleeping() {
return timeSpentSleeping;
}
public void setTimeSpentSleeping(int timeSpentSleeping) {
this.timeSpentSleeping = timeSpentSleeping;
}
#NonNull
#Override
public String toString() {
Gson gson = new Gson();
String json = gson.toJson(this);
return json;
}
static MyData build(final int timeSpentSleeping){
MyData newInstance = new MyData();
newInstance.timeSpentSleeping = timeSpentSleeping;
return newInstance;
}
}
And the react native module that do something and return objects of this class as javascript Promises:
public class HelloPromiseModule extends ReactContextBaseJavaModule {
public HelloPromiseModule(#NonNull ReactApplicationContext reactContext) {
super(reactContext);
}
#NonNull
#Override
public String getName() {
return "HelloPromise";
}
#ReactMethod
public void foobar(Promise promise){
Random r = new Random();
final int timeToSleep = r.nextInt(1000);
runThreadAndCallPromiseToJavascript(timeToSleep, promise);
}
//Cria um thread pra executar algo em paralelo
private void runThreadAndCallPromiseToJavascript(final int timeToSleep,final Promise promise){
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(timeToSleep);
MyData result = MyData.build(timeToSleep);
promise.resolve(result.toString());
} catch (InterruptedException e) {
e.printStackTrace();
promise.reject(e);
}
}
});
t.run();
}
}
Now, we create the React Native Package (that is different from java packages):
public class HelloWorldPackage implements ReactPackage{
#NonNull
#Override
public List<NativeModule> createNativeModules(#NonNull ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new HelloPromiseModule(reactContext));
}
#NonNull
#Override
public List<ViewManager> createViewManagers(#NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
The last step in the android version of your react native app is to register your HelloWorldPackage:
In the MainApplication.java inside your android project, inside the getPackages(), in the list of packages (new PackageList(this)...):
packages.add(new HelloWorldPackage());
Something like that:
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new HelloWorldPackage());
return packages;
}
Now, to get your native class in the javascript world:
import {
NativeModules,
} from 'react-native';
...
const {HelloPromise} = NativeModules;
Your native class is accessible from the variable HelloPromise.
You can get the result of HelloPromise.foobar() with something like this, in the react native side of your code:
async function handleHelloPromisesPress() {
let result = await HelloPromise.foobar();
console.log(result);
}
You may notice that 'result' is a json whose structure is equal to the POJO class we created in the beginning.

Array of class and creating objects in typescript

I have a class like this and need to create a collection of properties .in c# i can use a list or any collection type but how to do it in typescript .
class Movies implements Imovies{
public Id : string;
public get fid(): string {
return this.Id;
}
public set fid(theid:string) {
this.Id=theid;
}
public dailyrentalRate : number;
public get fdailyrentalRate(): number {
return this.dailyrentalRate;
}
public set fdailyrentalRate(theid:number) {
this.dailyrentalRate=theid;
}
public numberinstock : number;
public get fnumberinstock(): number {
return this.numberinstock;
}
public set fnumberinstock(theid:number) {
this.numberinstock=theid;
}
public publishDate : string;
public get fpublishDate(): string {
return this.publishDate;
}
public set fpublishDate(theid:string) {
this.publishDate=theid;
}
public title : string;
public get ftitle(): string {
return this.title;
}
public set ftitle(theid:string) {
this.title=theid;
}
}
I tried to insert values to array as follows
let mov=new Array<Movies>();
mov[0].fid="asdasd";
mov[0].fdailyrentalRate=2;
mov[0].fnumberinstock=5;
mov[0].fpublishDate="2018-05-23";
mov[0].ftitle="name";
mov[1].fid="asdasda";
mov[1].fdailyrentalRate=32;
mov[1].fnumberinstock=35;
mov[1].fpublishDate="2018-06-23";
mov[1].ftitle="name2";
but is showing an error
TypeError: Cannot set property 'fid' of undefined
you can also implement the class Movie using a constructor, and then create an array of Movie, like this:
const movies: Movie[] = [];
after you could push movie objects in the movies array:
const movie = new Movie();
movie.fid="test1";
movie.dailyrentalRate=2;
movie.numberinstock=5;
movie.publishDate="2018-05-23";
movie.title="name";
movies.push(movie);
you can see a working example here: https://stackblitz.com/edit/typescript-array-movies

Angular4/TypeScript Class Usability

Is that possible to access two different Typescript classes like controller to store a value...here is my use case....
i'm getting values from the front end lets say i have ID="100",Name="Angular4". Now how can i pass those values to these class using the methods get getFieldValue(fieldName: string) and setFieldValue(fieldValue: string, value: string). Also i have tried to instantiate the classes to get or set the value but i got failed,can anybody please tell how can i acheive the desired output completely using typescript?
my classes are:
main class:
import {Record} from './record';
import {Field} from './field';
export class BusinessObject {
public boName: string = null;
public focusedRecordsList = new Set();
// public activeRecord: Record = new Record();
public fetchSize: number = 100;
// public activeParentRecord: Record = new Record();
public hasMoreRows: boolean;
public isPageQuery: boolean;
public startIndex: number;
public createNewRecord(boName: string, parentId: string, fromRecord: string) {
return JSON.stringify({'boName': boName, 'parentId': parentId, 'fromRecord': fromRecord});
}
getFieldValue(fieldName: string): any {
}
setFieldValue(fieldValue: string, value: string): void {
}
}
and another class, that contains my field types:
import {BusinessObject} from './business-object';
export class Field extends BusinessObject{
// Specifies different information on the field
public name: string = null;
public id: string = null;
public type: string = null;
public boId: string = null;
public colName: string = null;
constructor(name: string) {
}
}

Cnverting JSON to Java Object using GSON

Can you please let me know what went wrong in the below sample.
Employee.java
public class Employee {
private String name;
public String getName() {
return name;
}
public String getAge() {
return age;
}
private String age;
}
JsontoJava.java
import com.google.gson.Gson;
public class JsontoJava {
public static void main(String ar[]){
Gson gson = new Gson();
String json = "{\"Employee\":[{\"name\":\"Test\", \"age\":\"12\"}]}";
Employee staff = gson.fromJson(json, Employee.class);
System.out.println("Name : "+staff.getName());
}
}
Unfortunately getting the wrong output:
Name :null
Your json is not right. Change to this.
{"name":"Test","age":"12"}

Categories

Resources