I am getting object in the response of entityManager.find method.
and i want to get values from that object by passing key. but i din't get any success.
For example :-
my entity :-
#entity
class Test (){
public Long id;
public String name ;
public String descr;
}
and i am getting object in the response of below code.
`Object obj=`entitymanager.find(classname,id);
Note :- Instead of object i can't use entity's object directly because input class name can be dynamically pass that's why i am taking response in Object.
Now i want to get value from object by passing key
something like that obj.getvalue("id");
I tried below things to make it done :-
Map<String, Object> user = (Map<String, Object>)obj;
Used json simple parser to parse it.
JSONParser parser = new JSONParser();
JSONObject jsonObject =parser.parse(obj.toString());
But din't get any success.
Please help me out.
I'm a little unsure of what you're asking... but as long as "name" is a primary key you can call
Test obj = entitymanager.find(Test.class, name);
Object obj=entitymanager.find(classname,id);
In the above line what is the type of "classname".
Since your question does not mention the type. I assume its of type Object.
You should do something like
Object obj=entitymanager.find(classname.getClass(),id);
Related
I have the following request with these fields:
Payment (Type Payment) -> Parameters (Type Object).
I know this Parameters class has these fields:
token (String)
type (String)
cvv (String)
I´m trying to have access to the field token through request.getPayment().getParameters() but I don't really know how to make it work. I found something related to Reflection but I don´t really know how it can work.
I've tried something like but I still don't know howo to fetch this String "token":
Field field = org.springframework.util.ReflectionUtils.findField(String.class, "token");
org.springframework.util.ReflectionUtils.makeAccessible(field);
String token = field.get(request.getPayment().getParameters().????) ????
If you sure that you will always have these fields in this generic object, you can just use casting:
class PaymentParameter {
String token;
String type;
String cvv;
... // getters & setters or Lombok stuff
}
...
var paymentParameters = (PaymentParameters) request.getPayment().getParameters();
You can read more about casting here and here.
Please be aware that casting can throw ClassCastException. So you have to cover this case in your code.
The second option is that your request is a JSON string, then you can use Jackson to convert it to the map or object. This topic is covered also on Baeldung.
Is there a way to get the type of a parameter using the thrift ID? I have data coming in that needs to go to one of 6 different Thrift objects so I'm using reflection to instantiate the appropriate object and set data fields.
Class<?> cls = Class.forName(package + table.name);
Object o = cls.newInstance();
Method getField = cls.getMethod("fieldForId", int.class);
Object field = getField.invoke(o, thriftId);
Method setField = cls.getMethod("setFieldValue", field.getClass(), Object.class);
setField.invoke(o, field, data);
The variable data is a String. This code works great until it comes across a field with a type other than String where I can get ClassCastException. I tried doing this:
Method getFieldValue = cls.getMethod("getFieldValue", field.getClass());
System.out.println(getFieldValue.invoke(o, field).getClass.getName());
But for String, getFieldValue returns null if they are blank and you can't get the class. I could assume that all null values are Strings, but that seems dangerous considering Lists, Maps, etc are probably returned as null as well.
I also tried getting the Class of the field but it just comes back as the Enum (_Fields) which is expected.
I managed to find a solution. Grab the name of the field then get that field.
Method getFieldName = field.getClass().getMethod("getFieldName");
String fieldName = (String) getFieldName.invoke(field);
Class<?> fieldType = cls.getField(fieldName).getType());
I have a class Person and I want to deserialize a POJO from a JSON using jackson. Now,
the definition to Person class is something like :
class Person {
int id;
String name;
boolean isOldAge;
boolean hasSenseOfHumor;
.
.
.
}
Now my json is something like :
{
"id" : 1,
"isOldAge" : false
}
Now when I deserialize this into a POJO the values I will get would be :
[id=1,name="",isOldAge=false,hasSenseOfHumor=false]
i.e, the properties not mentioned in json will be assigned their default values.
So my problem lies here. Is there a way I can distinguish isOldAge from hasSenseOfHumor with respect to whether it is mentioned or provided for by the user or not.
Try to change the primitive boolean to the boxing Boolean type. The fields should be initialised with null values then.
If you cannot change field types of the class, then can read your JSON as map in advance as follows mapper.readValue(JSON, Map.class), and then reason about the presence of the boolean fields in the resulting map instance.
I am playing with flexjson and Google Cloud Endpoints. My model which I need to serialize is:
public class SampleModel {
Long id;
DateTime createdAt;
String message;
OtherModel other;
}
I just created DateTimeObjectFactory to find a way of creating DateTime objects (lacks of no arg constructor). Now I have question about OtherModel and SampleModel as well.
I want to serialize in fact a List of SampleModel. So here is my code:
List<SampleModel> sampleList = new ArrayList<SampleModel>();
// ...
// adding some items to sampleList
// ...
String s = new JSONSerializer().deepSerialize(sampleList);
I want to deepSerialize it for now to avoid some unserializated fields, but just for now.
When I want to deserialize s I do that:
sampleList = new JSONDeserializer<List<SampleModel>>()
.use("other", OtherModel.class)
.use(DateTime.class, new DateTimeObjectFactory())
.deserialize(s);
I think that everything is just ok in that kind of deserializing, because I can see in logs deserialized object. But in fact when I want to get item from that new sampleList I get an error:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.test.games.testapi.model.SampleModel
If I have good understanding every not trivial object will be deserialized as Map if I don't point the right class to deserializer. So this error means that script didn't know SampleModel? What is the meaning of this?
Is their an easy way or library to convert a JSON String to a Java object such that I can easily reference the elements in a JSP page? I think Map's can be referenced with simple dot notation in JSP pages, so JSON -> Map object should work?
UPDATE: Thank you for all the JSON Java libraries. In particular, I'm looking for a library that makes it easy for consumption in JSP pages. That means either the Java object created has appropriate getter methods corresponding to names of JSON nodes (is this possible?) or there's some other mechanism which makes it easy like the Map object.
Use Jackson.
Updated:
If you have an arbitrary json string Jackson can return a map object to access the properties values.
Here a simple example.
#Test
public void testJsonMap() throws JsonParseException, JsonMappingException, IOException {
String json = "{\"number\":\"8119123912\",\"msg\":\"Hello world\"}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
System.out.println("number:" + map.get("number") + " msg:" + map.get("msg"));
}
Output:
number:8119123912 msg:Hello world
Try GSON, here is a tutorial.
This library should do what you want: http://www.json.org/java/
DWR can be used for this purpose DWR - Easy Ajax for JAVA .
Lets consider this java class.
class Employee
{
int id;
String eName;
// setters and getters
}
In javascript JSON object
var employee = {
id : null,
name : null
};
This is the call to java method from javascript function.
EmployeeUtil.getRow(employee,dwrData);
In getRow() of EmployeeUtil class, return type of method will be Employee.
Employee getRow();
So using the setters of Employee set the data.
dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned which is Employee bean will be in callback function.
Just initialize this in javascript JSON object.
Now the JSON object can be parsed and displayed in jsp.
This example shows Dynamically Editing a Table
Hope this helps ....