Return String from Query with CouchbaseTemplate.findByN1QLProjection

Hello everyone I am working now with Spring-data-Couchbase I’m doing the next query:

@Override
public String findRoomIdBetweenMinAgeAndMaxAge(int kidAge, String id, String kidId) {
String query = buildFindRoomByKidAge();
JsonObject params = JsonObject.create()
.put(JAVA_TYPE_PARAM, ShipRoom.class.getName())
.put(ID_PARAM, id)
.put(KID_AGE_PARAM, kidAge);

    N1qlQuery queryWithParameter = N1qlQuery.parameterized(query, params);
    
    String roomId = template.findByN1QLProjection(queryWithParameter, String.class)
            .stream()
            .findFirst().orElseThrow(() -> new RoomNotFoundException(buildNotRoomForKidAgeMessage(kidId)));
    if (roomId.isEmpty()) {
        throw new RoomNotFoundException(ROOM_ID_EMPTY);
    }
    return roomId;
}

This is the buildFindRoomByKidAge method:

private String buildFindRoomByKidAge() {
return new StringBuilder(“SELECT rd.id”)
.append(" FROM “).append(template.getCouchbaseBucket().name())
.append(” as kc USE KEYS $“).append(ID_PARAM)
.append(” UNNEST kc.rooms rd")
.append(" WHERE rd.minAge <= " + KID_AGE_PARAM + " AND rd.maxAge >= " + KID_AGE_PARAM)
.toString();
}

I’m trying to return a String form in the line:

String roomId = template.findByN1QLProjection(queryWithParameter, String.class)

but I’m getting the next issue: Cannot decode ad-hoc JSON

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (String)“{“id”:”“}”; line: 1, column: 1]

I’m no pretty sure about the cause of this issue. Thanks for any advice.

At first glance, I believe that the query returns {“id”:""}, and you are trying to deserialize into a string. The deserializing sees it is an object, and raises an exception, I believe.

Perhaps deserializing into a JavaObject instead, then get the value of the “id” field instead? I’ll try that out later myself and be sure that’s it.