Cnverting JSON to Java Object using GSON - javascript

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"}

Related

How can I get a data from Spring-Security principal?

Now I face with some problems about principal data. Maybe it sounds like a fool. But I'm new to Spring..
I wanted to get some specific data from principal data, but it occured an error, So I cant.
this is my customUserDetails that implement UserDetails.
private String id;
private String pw;
private String name;
private String auth;
private String level;
private String label;
private int enabled;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
ArrayList<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
authList.add(new SimpleGrantedAuthority(auth));
return authList;
}
#Override
public String getPassword() {
return pw;
}
#Override
public String getUsername() {
return id;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled==1?true:false;
}
public String getName() {
return name;
}
public String getLabel() { return label;} // 4월 19일 동현 추가
public void setName(String name) {
this.name = name;
}
public String getAuth() {
return auth;
}
And this is principal data I got from console.log
CustomUserDetails(id=admin, pw=$2a$10$Z9C0gTGV0weknBvNi4YFY.l41vjrYo4UgO3MlPwgmIn4uDeYlepFq, name=Admin, auth=ROLE_ADMIN, level=null, label=N, enabled=1)
I want to extract label value from Principal, so I tried to do this code, but I can't.
console.log('${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.label}');
How can I get 'label' data from principal?
Thank you for your kind support :)
In your Controller or any other bean, autowire user details like
public String doSomething(#AuthenticationPrincipal CustomUserDetails userDetails) {
String label = userDetails.getLabel();
}

Spring boot jpa can't insert row with string containing accents

I can"t understand the problem because i found nowhere the same problem.
i tried to insert product with type "pièces détachées". On the browser path /Produits the product doesn't show up but when i remove the accents from the string it's inserting in the mysql db. I tried to insert accents in the db the query is ok. But with my code it's impossible to do the same. here's a sample of my code for Produit :
//ajouter un produit
#PostMapping(value = "/Produits")
public ResponseEntity<Void> ajouterProduit(#RequestBody ProduitDTO produit) {
Produit produitCK = new Produit();
produitCK.setIdPM(new ProduitMagasin(produit.getId(), produit.getIdMagasin()));
produitCK.setDateAjout(produit.getDateAjout());
produitCK.setEtatProduit(produit.getEtatProduit());
produitCK.setIdReference(produit.getIdReference());
produitCK.setNumeroSerie(produit.getNumeroSerie());
produitCK.setPrixVente(produit.getPrixVente());
produitCK.setTVA(produit.getTVA());
produitCK.setType(produit.getType());
Produit produitAdded = produitDao.save(produitCK);
if (produitAdded == null)
return ResponseEntity.noContent().build();
else
return new ResponseEntity<>(HttpStatus.CREATED);
}
ProduitDTO :
package com.stationphone.db.model;
import java.sql.Timestamp;
/**
*
* #author Administrateur
*/
public class ProduitDTO {
private int id;
public enum Type {
PIECES {
public String getString() {
return "pièces detachées";
}
},
VENTE {
public String getString() {
return "vente en magasin";
}
};
public abstract String getString();
}
private String type;
private int id_reference;
private String numero_serie;
private Timestamp date_ajout;
private String marque;
private String modele;
private float prix_vente;
private double prixHT;
private float tva;
private String etat_produit;
private int id_magasin;
public int getId(){
return this.id;
}
public void setId(int id){
this.id=id;
}
public int getIdOnline(){
return this.id;
}
public void setIdOnline(int id){
this.id=id;
}
public String getType(){
return this.type;
}
public void setType(String type){
this.type=type;
}
public int getIdReference(){
return this.id_reference;
}
public void setIdReference(int id_reference){
this.id_reference=id_reference;
}
public String getNumeroSerie(){
return this.numero_serie;
}
public void setNumeroSerie(String numero_serie){
this.numero_serie=numero_serie;
}
public Timestamp getDateAjout(){
return this.date_ajout;
}
public void setDateAjout(Timestamp date_ajout){
this.date_ajout=date_ajout;
}
public String getMarque(){
return this.marque;
}
public void setMarque(String marque){
this.marque=marque;
}
public String getModele(){
return this.modele;
}
public void setModele(String modele){
this.modele=modele;
}
public float getPrixVente(){
return this.prix_vente;
}
public void setPrixVente(float prix){
this.prix_vente=prix;
}
public double getPrixHT(){
return this.prixHT;
}
public void setPrixHT(double prix){
this.prixHT=prix;
}
public float getTVA(){
return this.tva;
}
public void setTVA(float tva){
this.tva=tva;
}
public String getEtatProduit(){
return this.etat_produit;
}
public void setEtatProduit(String etat){
this.etat_produit=etat;
}
public int getIdMagasin(){
return this.id_magasin;
}
public void setIdMagasin(int id_magasin){
this.id_magasin=id_magasin;
}
}
class Produit :
package com.stationphone.db.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
/**
*
* #author Administrateur
*/
#Entity
public class Produit implements Serializable {
#EmbeddedId
private ProduitMagasin idPM;
#OneToOne
#JoinColumn(name = "id_magasin", insertable=false, updatable=false)
Magasin magasin;
public enum Type {
PIECES {
public String getString() {
return "pièces detachées";
}
},
VENTE {
public String getString() {
return "vente en magasin";
}
};
public abstract String getString();
}
private String type;
private int id_reference;
private String numero_serie;
private Timestamp date_ajout;
private float prix_vente;
private float tva;
private String etat_produit;
public ProduitMagasin getIdPM(){
return this.idPM;
}
public void setIdPM(ProduitMagasin id){
this.idPM=id;
}
public String getType(){
return this.type;
}
public void setType(String type){
this.type=type;
}
public int getIdReference(){
return this.id_reference;
}
public void setIdReference(int id_reference){
this.id_reference=id_reference;
}
public String getNumeroSerie(){
return this.numero_serie;
}
public void setNumeroSerie(String numero_serie){
this.numero_serie=numero_serie;
}
public Timestamp getDateAjout(){
return this.date_ajout;
}
public void setDateAjout(Timestamp date_ajout){
this.date_ajout=date_ajout;
}
public float getPrixVente(){
return this.prix_vente;
}
public void setPrixVente(float prix){
this.prix_vente=prix;
}
public float getTVA(){
return this.tva;
}
public void setTVA(float tva){
this.tva=tva;
}
public String getEtatProduit(){
return this.etat_produit;
}
public void setEtatProduit(String etat){
this.etat_produit=etat;
}
}
I hope i'll find an answer here. Thanks.
EDIT : the post method :
public static HttpResponse post(Object object, String type){
HttpResponse response=null;
try{
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(getUrl(type));
System.out.println(getUrl(type));
ObjectMapper mapper= new ObjectMapper();
String jsonInString = mapper.writeValueAsString(object);
System.out.println(jsonInString);
StringEntity input = new StringEntity(jsonInString);
input.setContentType("application/json");
postRequest.setEntity(input);
response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
System.out.println(response.getStatusLine().getStatusCode()+" ");
client.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
return response;
}
EDIT 2 : the error on tomcat local :
018-07-24 18:55:32.196 WARN 10860 --- [nio-8084-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP
message:
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Invalid UTF-8 middle byte 0x63
at [Source: (PushbackInputStream); line: 1, column: 21]; nested
exception is com.fasterxml.jackson.databind.JsonMappingException:
Invalid UTF-8 middle byte 0x63
at [Source: (PushbackInputStream); line: 1, column: 21]
at [Source: (PushbackInputStream); line: 1, column: 16] (through
reference
chain: com.stationphone.db.model.ProduitDTO["type"])
Thanks tp billy frost what to do 2 things :
HttpPost postRequest = new HttpPost(getUrl(type));
postRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity input = new StringEntity(jsonInString, "UTF-8");

Can I display JSON Data with an SQL Query?

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!!

How to define array property using jsinterop?

I am trying to define a javascript type using JsInterop but could not figure out how to define an array propery inside a type.
#JsType
public interface Task
{
// this works
#JsProperty String getTitle();
#JsProperty void setTitle(String title);
}
#JsType
public interface ViewModelInterface
{
// the following works
#JsProperty String getValue();
#JsProperty void setValue(String val);
// this does not work
#JsProperty Task[] getTasks();
#JsProperty void setTasks(Task[] tasks);
}
Is there any special syntax I should use?
Update:
I have come up with a temporary solution to the problem. I tried to use JNSI together with JsInterop and because the type define is javascript type we can add any property in that type after it is initialized.
The code is here
public class ViewModel implements ViewModelInterface
{
private String value;
public ViewModel()
{
value = "";
initTasksArray();
}
public String getValue() { return value; }
public void setValue(String val) { this.value = val; }
private native void initTasksArray()
/*-{
this.tasks =
[
{ title: 'Get high enough to grab the flag' },
{ title: 'Find the Princess' }
];
}*-/;
}
This way, the tasks property can be accessed from javascript as if it is defined as a #JsProperty. This is only a temporary solution and I am sure there will be a more proper one when JsInterop formally come out.
It should work as described.
Here is an example:
#JsType
public interface Task {
#JsProperty
String getTitle();
#JsProperty
void setTitle(String title);
public static Task getTask(String title) {
return new Task() {
private String title;
#Override
public String getTitle() {
return title;
}
#Override
public void setTitle(String title) {
this.title = title;
}
};
}
}
and
#JsType
public interface ViewModel {
#JsProperty
Task[] getTasks();
#JsProperty
void setTasks(Task[] tasks);
public static ViewModel getModel() {
return new ViewModel() {
Task[] tasks;
#Override
public void setTasks(Task[] tasks) {
this.tasks = tasks;
}
#Override
public Task[] getTasks() {
return tasks;
}
};
}
}
and the Javascript:
var model = ViewModel.getModel();
model.tasks = [Task.getTask('title1'), Task.getTask('title2')];
alert(model.tasks);

JSON serialization - how to unquote a property value?

Given a class A ...
public class A {
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
string jsonString = JsonConvert.SerializeObject(
new A() {
Prop1 = "ABC",
Prop2 = "$.jqplot.DateAxisRenderer" }
);
jsonString contains...
"{
\"Prop1\":\"ABC\",
\"Prop2\":\"$.jqplot.DateAxisRenderer\"
}";
Question:
How can I unquote Prop2?
i.e. I want jsonString to contain...
"{
\"Prop1\":\"ABC\",
\"Prop2\":$.jqplot.DateAxisRenderer
}";
so that Prop2 is evaluated (on the client) as a reference and not a string
If you want to remove the quotes from Prop2, you can write a JSON.NET JsonConverter for the type and output the property value as 'raw'.
However (and this is important), your output will no longer be valid JSON.
If you're happy with this hybrid solution, some example code is as follows (assuming you've already referenced JSON.NET in your project):
namespace JsonRawTest
{
public class AConverter : JsonConverter
{
public override bool CanRead { get { return false; } }
public override bool CanWrite { get { return true; } }
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
A obj = value as A;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(obj.Prop1);
writer.WritePropertyName("Prop2");
writer.WriteRawValue(obj.Prop2);
writer.WriteEndObject();
}
public override bool CanConvert(Type objectType)
{
return typeof(A).IsAssignableFrom(objectType);
}
}
public class A
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var a = new A
{
Prop1 = "Some first value",
Prop2 = "$.jqplot.DateAxisRenderer"
};
string json = JsonConvert.SerializeObject(a,
new JsonConverter[] { new AConverter() });
...
}
}
}
You can pass it to the client as a string and then use the eval() function to parse the string like so:
var str = "alert('hello')";
eval(str); //This will execute the alert method.
var str2 = "(function() { return true; })()";
var returned = eval(str2); //Holds value of true

Categories

Resources