jackson - Unable to deserialize string into java object - Cannot construct instance of `Address` - Stack Overflow
java - JSON: InvalidFormatException: Can not construct instance of int from String value - Stack Overflow
Can not construct instance of java.lang.Long from String value
java - Method to construct instances from strings and return them with their type? - Stack Overflow
You have two attributes called "linkLabel" in each of the JSON objects. Attribute names in a JSON object have to be unique if you want them to be extracted correctly by a standard JSON parser.
What is going to happen is that one of the attributes is going to be ignored (silently) by the JSON parser. For example:
"listLinkLabel": [{
"linkLabel": 1,
"linkLabel": "after"
}]
Assuming that the first attribute is the one that is ignored, your code will then try to convert "after" to an integer ... which will fail.
Basically, your JSON is (semantically) malformed, and you need to correct whatever is generating it.
UPDATE - I think I have figured out why Jackson is generating malformed JSON. You have:
@JsonIdentityInfo(
generator = ObjectIdGenerators.IntSequenceGenerator.class,
property = "linkLabel")
and also
@Column(name = "LinkLabel")
@GeneratedValue(strategy = GenerationType.AUTO)
private String linkLabel;
In other words, you have told Jackson that 1) there is a id attribute with type int and name linkLabel, 2) there is a property named linkLabel whose type is String.
Jackson has gotten a bit confused by this contradictory information, and assumed that you have specified there are two distinct attributes called linkLabel ... which doesn't work1.
You also >>appear<< to be trying to use linkLabel as a data field (with non-integer content) and that is also problematic2.
Solution: either get rid of the @JsonIdentityInfo annotation, or change it to use a distinct property name, and declare the corresponding Java field with the correct Java type.
1 - It doesn't work with the Jackson parser ... but you could make it work with a custom parser. Hence, there is a (tenuous) justification for Jackson to do this rather than treating this as an error.
2 - There is no way that Jackson could figure this one out ...
If you're using Google's Endpoints Framework: Be sure that any parameters specified in your @Api annotation's @Named are unique regardless of any other objects passed in as part of the body. If you use the @Named parameter "id" and also have an object with the same parameter, Endpoints will get confused.
This appears to be a bug in the Endpoints implementation as the specification should differentiate between serialized values in the path and those in the body: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object
For example, if you have:
class MyData {
private Long id;
public Long getId(){return id;}
public void setId(Long v){id = v;}
}
@Api( /* Your API stuff here */ )
class EndpointBase {
@ApiMethod(
name = "thingGet",
httpMethod = "GET")
public KnockerResponse thingGet(
@Named("id") String thingId,
MyData data
) {
// Never executes
}
}
You'll see your Endpoints server throw:
[INFO] INFO: exception occurred while calling backend method [INFO] com.google.api.server.spi.response.BadRequestException: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.lang.Long from String value 'EXAMPLEUUID': not a valid Long value [INFO] at [Source: N/A; line: -1, column: -1] (through reference chain: com.example.package.MyData["id"]) [INFO] at com.google.api.server.spi.request.RestServletRequestParamReader.read(RestServletRequestParamReader.java:128)
Endpoints Framework sees the @Named("id") thingId field and is de-serializing it into MyData, which is not per-spec or desired. Simply re-naming the parameter will fix this: @Named("thingId") thingId.
You need to tokenize the String.
(if it always starts with f( and ends with ) you can make your life easier, be removing these parts).
A(4) -> Find the Classname -> A -> find the Parameter -> 4
This is done like this (pseudo java code):
public static Object createClass(String className, Double value){
Class a = Class.forName(className);
Class[] params = new Class[]{Integer.class};
Constructor c = a.getConstructor(params);
Object[] values = new Object[]{value};
return c.newInstance();
}
Maybe, this lik is helpful: http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
update This is like writing a compiler. You can get further information, if you read something about, how to write a compiler: http://en.wikipedia.org/wiki/Compiler
update 2 put all generated instances into an array. Now you can get the correct method f with the reflections-API. The Code will be something like
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredMethod(java.lang.String, java.lang.Class...)
Object[] values ...
Class[] classes ...
for(Object o: values){
add o.getClass() to classes
}
Method f = Functions.getClass().getDeclaredMethods("f", classes);
f.invoke(values);
I think you should create a class for each function and call a static method like "compute". This way you parse the class name and attributes from the String and load the appropiate class via an class loader. You can pass a variable amount of parameters via an array or variables with a HashMap which contains the name as key and the variable as value.
If you remove your constructor declaration from the Student class, then the implicit empty constructor will exist.
But if you declared explicitly a constructor like your public Student(String firstname, String surname, String total) then the empty constructor won't be available, unless you add it explicitly to your class.
public Student() { };
Then you call unexistant methods :
newStudent.firstName("my name");
The method you want to call, as declared in your Student object is setFirstName(String firstName)
Finally in your println calls, you are trying to access the attribut of the object directly instead of using the getters methods.
You Student class don't have an empty constructor like youd do :
Student newStudent = new Student();
So you have a Constructor which should take three String :
public Student(String firstname, String surname, String total) {
So to solve your problem you have two ways :
1st
Create an empty constructor that not take any attribute like this :
public Student() {
}
and you can put your values with setAtt for example :
newStudent.setFirstName("my name");
2ed
You should to call your constructor with the three value like this :
Student newStudent = new Student("name 1", "name 2", "name 3");
Note
You can't set a value to an attribute in another class like this :
newStudent.firstName("my name");
You can make it like this :
newStudent.firstName = "my name";
import java.util.*;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Sample_String
{
String s;
Sample_String()
{
this.s=s;
}
public void input()
{
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(i);
System.out.println("Enter a Sentence");
s=br.readLine();
}
public void display()
{
System.out.println("The entered String was as follows "+s);
}
public static void main()
{
Sample_String ob = new Sample_String();
ob.input();
ob.display();
}
}java cannot magically cast one object to any another object unless they have parent child relationship.
casts won't work in that way.
All String's are Object's. But not all Object's are String's.
Edit to comment(u mean down casting is not possible in java):
No. I didn't mean that. Down casting is possible in the cases like
Object obj = getThat();
String s = (String) obj;
Possible, if you see. The above code executes fine if getThat() method returns a String. Otherwise a Exception.
Same rule applies to getResponse() method too.
This will only work if Request is also a subclass of String (which is probably isn't in your case). What you can do though is this:
String s1=req.getResponse().toString();
You are definitely reinventing the wheel
Java Object Serialization already does this, albeit that the serialization format is binary (and opaque).
Various JSON (or XML) <-> POJO binding mechanisms already do this, albeit that the serialization format can be verbose.
(Now there are limits to what these schemes can do. For example, they cannot serialize a Thread or a Socket. But neither can your proposal ... for the same reasons. These classes have state that simply cannot be captured in a serialization.)
But if you really want to invent the wheel, you can do it.
As noted, you can use reflection to access and call a public or private constructor on a non-abstract type.
There is also an "under the hood"
Unsafemechanism that JOS uses to create objects without invoking any constructor. Combine this withUnsafemethods for assigning values to fields.
However, your approach implicitly assumes that the toString method returns a string that can be used later to reconstruct the object. This is not true, in general.
- The default implementation returns a string consisting of the object's class name and its identity hashcode. (An example of the types affected by this is any array type.) You can't reconstruct an object from that.
- And even for cases where the
toStringresult does include the information needed for deserialization, the string format is rarely standardized. (TheCollectionAPIs are the exception ...)
In short, toString is not the answer.
You are kinda reinventing the wheel.
For your question first, you need to know which User class you want to deserialize. Your stringified form should look somewhat like this:
my.package.name.User(java.lang.String, int)
my.package.name.User: variables...
Otherwise, how would you know is it my.package.User or my.package.name.User? Of course, you could write a custom adapter for this "figuring out" phase to get the full class name but I guess you shouldn't.
// You can directly parse the parameter classes, technically you don't need it
// at method parameter. You can include it if you feel like it's easier to work
// with predefined values.
public Object toObject(String string) throws Exception {
// get your full class name here first
// parse it first or whatever
String className = getConstructorClass(params1);
String[] parameterClassName = getConstructorParameterClassNames(params2);
String[] parameterStringifiedValue = getParameterValues(params3);
Class<?> clz = Class.forName(className);
@SurpressWarning("unchecked") // List<Class<?>> is the same anyway
Class[] parameterClasses = // repeat Class.forName()...
Object[] parameters = // An example, for(int i=...
// parameterClasses[i]
// .getDeclaredConstructor(String.class)
// .newInstance(parameterStringifiedValue[i]);
return clz
.getDeclaredConstructor(constructorParamClasses)
.newInstance(parameters);
}
This whole parsing is so painful ngl. You probably want to use Java built-in serialization support or parse from a well-supported format (xml, json...) and let libraries do all the intricacies.
You can use generic for as a more type-safe approach, but requires more knowledge from calling context.
public <T> T toObject(Class<T> objectType, String string) {
return objectType.getDeclaredConstructor(...).newInstance(...);
}
hi all, very new to Java so please excuse my question.
I am getting an error message & I am sure that I am doing something wrong but I can't seem to think of it. Can someone please help?
for (long i = 0; i < 10; i++) {
final String orderId = "id" + Long.toString(i);
final Payment payment = new Payment(orderId, 1000.00d);
Thread.sleep(1000L);
}https://pasteboard.co/JViGoDg.png