The error you are facing is based on objectmapper convertvalue-vs-readvalue.

Basically, what objectMapper.convertValue(addressDetail, Address.class) tries, is to create an Address from the single string value you pass in. It does not read the string contents and set field values. If you need to use convertValue, then you have to create a constructor like public Address(String json){/*do mapping manually here*/}.

The better approach however would be to use objectMapper.readValue(addressDetail, Address.class), as this method actually traverses the JSON string and creates an instance with the fields you have present in the string. readValue only requires getter/setter and an no-args constructor to function

Answer from XtremeBaumer on Stack Overflow
🌐
Camunda
forum.camunda.io › camunda 7 topics › discussion & questions
Cannot construct java type from string error - Discussion & Questions - Camunda Forum
June 18, 2017 - Hi, I deployed a process before and worked well. But now I change in BPMN and when deploying this new version and start a process instance with REST-API, I got 500 internal server error with below message: "Cannot instantiate process definition first-archive:2:1adca1f5-53f1-11e7-ac84-6451060de7a8: Error while evaluating expression:Get file of ${session.getSessionName()}. Cause: Cannot deserialize object in variable 'session': SPIN/JACKSON-JSON-01007 Cannot construct java type from string 'com....
🌐
Baeldung
baeldung.com › home › json › jackson › jackson exceptions – problems and solutions
Jackson Exceptions - Problems and Solutions | Baeldung
April 8, 2024 - com.fasterxml.jackson.databind...ppingException.from(JsonMappingException.java:148) To solve this problem, we just add a default constructor: public class User { public int id; public String name; public User() { super(); } ...
Discussions

jackson - Unable to deserialize string into java object - Cannot construct instance of `Address` - Stack Overflow
I have a string which I'm supposed to read into an address object. Now the string I'll get may contain some extra fields and may not contain some fields which is declared in my Address class. I've More on stackoverflow.com
🌐 stackoverflow.com
May 10, 2022
java - JSON: InvalidFormatException: Can not construct instance of int from String value - Stack Overflow
I have this weird problem that when the server receives a JSON via REST, Jackson tries to convert a String into an Integer: BlockquoSchwerwiegend: The exception contained within More on stackoverflow.com
🌐 stackoverflow.com
January 2, 2016
Can not construct instance of java.lang.Long from String value
There was an error while loading. Please reload this page · Exception : com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.lang.Long from String value ("2774.64000000"): not a valid Long value at [Source: okhttp3.ResponseBody$BomAwareReader@4a1c12c; ... More on github.com
🌐 github.com
3
April 30, 2021
java - Method to construct instances from strings and return them with their type? - Stack Overflow
The magic is done with ... is from type A. Thats why it will be passed to f(A) and not into f(B). 2013-01-12T23:06:25.837Z+00:00 ... 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 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Camunda
forum.camunda.io › camunda 7 topics › discussion & questions
Cannot deserialize object in variable 'test1': SPIN/JACKSON-JSON-01007 Cannot construct java type from string 'java.util.ArrayList<groovy.sql.GroovyRowResult<java.lang.Object,java.lang.Object>>' - #5 by Ali_Titan - Discussion & Questions - Camunda Forum
May 23, 2020 - @aravindhrs let me describe it from the beginning In the process start script. I fetch some data as an array and serialize the table data to JSON format like you see with no problem . then I will need this data in the next user task which I should show this data to user so I set table data (table data) as test1 variable. in the task form I have it as json object in javascript and no problem.But in the next task which I want to access this ‘test1’ variable the deserialization error occurs .
Top answer
1 of 2
2

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

2 of 2
0

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.

🌐
DataWider
datawider.com › articles › no string-argument constructor/factory method to deserialize from string value — jackson fix guide
No String-Argument Constructor/Factory Method to Deserialize from String Value — Jackson Fix Guide
May 5, 2026 - Jackson looks for a constructor or factory method that accepts a single String argument to create that object, and finds none · In plain terms: you mapped a JSON string value to a Java class, but that class doesn’t have a way to be constructed from a single string.
🌐
GitHub
github.com › binance-exchange › binance-java-api › issues › 359
Can not construct instance of java.lang.Long from String value · Issue #359 · binance-exchange/binance-java-api
April 30, 2021 - There was an error while loading. Please reload this page · Exception : com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.lang.Long from String value ("2774.64000000"): not a valid Long value at [Source: okhttp3.ResponseBody$BomAwareReader@4a1c12c; ...
Author: binance-exchange
Top answer
1 of 3
2

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);
2 of 3
0

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.

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 57199179 › how-to-fix-string-cannot-be-resolved-to-a-type › 57199557
java - how to fix 'String cannot be resolved to a type' - Stack Overflow
when i compile the code in eclipse, throwing error "Exception in thread "main" java.lang.Error: Unresolved compilation problems: String cannot be resolved to a type String cannot be reso...
🌐
Reddit
reddit.com › r/learnprogramming › error says incompatible types: java.lang.string cant be converted to string
r/learnprogramming on Reddit: Error says incompatible types: java.lang.string cant be converted to String
May 21, 2024 -
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();
    }
}
🌐
Stack Overflow
stackoverflow.com › questions › 74244816 › cannot-construct-instance-of-x-although-at-least-one-creator-exists-no-string
java - Cannot construct instance of X (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value - Stack Overflow
Any other alternative way to build testInput so that it can be correctly mapped to Request class when testing? ... Converting the json string to Object type using readValue() before passing it to the method under test resolved the error.
🌐
Camunda
jira.camunda.com › browse › CAM-11175
Loading...
December 9, 2019 - Problem: The MapJacksonJsonTypeDetector constructs the type of objects by using the first element inside the map. This leads to a situation where the object type name of complex variables name may change to a concrete type, but the serialized value cannot be deserialized anymore. ... ObjectValue variable = Variables .serializedObjectValue("{\"someObject\": [{\"firstItem\": \"aaa\", \"secondItem\": \"aaa\"}], \"otherItem\": \"\"}") .objectTypeName("java...
🌐
Coderanch
coderanch.com › t › 734028 › java › java-incompatible-types-java-lang
java: incompatible types: java.lang.String cannot be converted to com.orbitz.consul.model.kv.Value (Java in General forum at Coderanch)
August 30, 2020 - That's issue #2. The simple solution - fix the Map type in your test, change it to Map<String, Value>. You need to change the values you put in this Map because these need to be instances of Value. There may be a constructor that you can use; we don't know the class so we can't tell you for sure.
Top answer
1 of 2
3

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" Unsafe mechanism that JOS uses to create objects without invoking any constructor. Combine this with Unsafe methods 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 toString result does include the information needed for deserialization, the string format is rarely standardized. (The Collection APIs are the exception ...)

In short, toString is not the answer.

2 of 2
0

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(...);
}
🌐
javathinking
javathinking.com › blog › no-string-argument-constructor-factory-method-to-deserialize-from-string-value
How to Fix "No String-argument constructor/factory method to deserialize from String value ('')" Error in Jackson ObjectMapper (Java/Spring MVC) — javathinking.com
This error occurs when Jackson, the popular JSON processing library, tries to convert a JSON string (e.g., "123" or "") into a Java object but can’t find a valid way to construct that object from a string.