strip identifier from result of .toString() method - java

It is out of desperation and I don't know java. Basically, I want to resolve a couchbase lite Document back to a react-native application as follows:
Document doc = database.getDocumet('id');
promise.resolve(doc);
that doesn't work with error can't be cast so I turned to toString(), hoping to parse it in react-native:
promise.resolve(doc.toString());
// in js:
const document = getNativeDocument('id');
console.log(document)
const v = JSON.parse(document);
but that fails too with error:
SyntaxError: JSON Parse error: Unexpected identifier "Document"].
The console result is:
Document{#0xb3181c18e30a7f1-1f61-49a0-9ca0-1dc3d2e343ed#1-a7ed608736c34cf5860a0d35968e6441e1f089ef(..):obj=>Dictionary{(..)a=>A,b=>B},age=>20,firstPromo=>null}
I have tried solutions to convert the Document into other times that can easily be resolved by promise.resolve() but now wondering if there is away to work with results of the .toString()

the toString method generates an internal representation of the object for debugging, not JSON of the document. You need to use a different method to serialize your Document to JSON.
The most popular option for this is to use the Jackson library: https://www.baeldung.com/jackson-object-mapper-tutorial
If you're using Spring framework with Spring data couchbase connector then Jackson's ObjectMapper should already be available to your application as a Bean.

Related

Convert XML to and from Java

I am trying to get the XML response from the rest API. And I am getting JSON response for all customers and XML for single customer from API. PFB the screen print for the case for both cases:
Case 1: When URL= http://localhost:8080/spring-crm-rest/api/customers/ then I am getting JSON response
JSON Response
Case 2: When URL = http://localhost:8080/spring-crm-rest/api/customers/1 then I am getting XML response
XML Response
Please find below the URL for the complete code to replicate the same at your end.
Link for the code: https://drive.google.com/file/d/1fd7DyUsfOvY4fX0nm6j4fzrwxHyg9ZGz/view?usp=sharing
Ok I think the reason why that happens is the following:
the path /spring-crm-rest/api/customers/ has return type List<Customer> -> default java List as top level -> json result
while /spring-crm-rest/api/customers/1 has return type Customer as top level which has the javax.xml.bind annotations -> xml result
Changing this may be a bit tricky but these are some possible things you can try:
specifically set the content type of the endpoint like this: #GetMapping(produces = {"application/json"})
removing the #Xml.* annotations -> spring will can serialize the class without any annotations but without them you have less of a control over the resulting json (e.g. renaming fields, etc). Depending on your usecase it might not be needed though

MongoDB Projections.elemMatch in array returns empty document

So I'm using Mongo Atlas to train a bit with MongoDB.
I have loaded the sample data and I'm using the sample_airbnb.
Now what I am trying to do is go in the array of docs "reviews" and find a reviewer_name which is equals to "Philippe".
Here's how I proceed:
Document document = collection.find()
.projection(Projections.fields(Projections.include("name", "reviews"),
Projections.excludeId(),
Projections.elemMatch("reviews", Filters.eq("reviews.reviewer_name", "Philippe")))).first();
But this actually returns me an empty doc if I don't specify which fields to include. Even when I try to include other fields, it shows nothing:
Document{{name=Ribeira Charming Duplex}}
Here's a pastebin of the document I'd like to retrieve : https://pastebin.com/Vsu8yj6G

Jackson: Object to String via writeValueAsString: NPE

Im attempting to convert a Java Object into JSON using the Jackson parser. The original object comes to me via protobuf and contains some #annotations specific to Jackson.
When I call String jsonView = objectMapper.writeValueAsString(values);
I get this exception. The object doesn't contain any recursive values so I'm not clear why Im seeing this error (or even this code path).
ObjectMapper is configured with: objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); (although removing it doesn't seem to change anything)
java.lang.NullPointerException: null
at com.fasterxml.jackson.databind.type.ResolvedRecursiveType.equals(ResolvedRecursiveType.java:103)
at com.fasterxml.jackson.databind.type.TypeBindings$AsKey.equals(TypeBindings.java:458)
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:940)
at com.fasterxml.jackson.databind.util.LRUMap.get(LRUMap.java:68)
at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1211)
at com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(TypeFactory.java:1384)
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1154)
at com.fasterxml.jackson.databind.type.TypeFactory._resolveSuperInterfaces(TypeFactory.java:1298)
at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1243)
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1150)
at com.fasterxml.jackson.databind.type.TypeFactory._resolveSuperInterfaces(TypeFactory.java:1298)
at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1247)
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1150)
at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:618)
at com.fasterxml.jackson.databind.cfg.MapperConfig.constructType(MapperConfig.java:290)
at com.fasterxml.jackson.databind.cfg.MapperConfig.introspectClassAnnotations(MapperConfig.java:320)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.removeIgnorableTypes(BeanSerializerFactory.java:714)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanProperties(BeanSerializerFactory.java:573)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.constructBeanSerializer(BeanSerializerFactory.java:390)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanSerializer(BeanSerializerFactory.java:273)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:225)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:159)
at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1272)
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1243)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:535)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.resolve(BeanSerializerBase.java:332)
at com.fasterxml.jackson.databind.ser.SerializerCache.addAndResolveNonTypedSerializer(SerializerCache.java:174)
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1254)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:535)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.resolve(BeanSerializerBase.java:332)
at com.fasterxml.jackson.databind.ser.SerializerCache.addAndResolveNonTypedSerializer(SerializerCache.java:174)
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1254)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:535)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.resolve(BeanSerializerBase.java:332)
at com.fasterxml.jackson.databind.ser.SerializerCache.addAndResolveNonTypedSerializer(SerializerCache.java:197)
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1233)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:499)
at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:697)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:270)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3672)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3048)
Fixed in latest versions (see 2.8.1 or above):
https://github.com/FasterXML/jackson-databind/issues/1302

Generating Java code from transformation JSON to a XML

I wonder do you now any program that can generate for me a Java code from transformation JSON to a XML? In Altova MapForce there is such a possibility, but unfortunately when I want use it, it returns me an Error:
Altova_Hierarchical_JSON.mfd: Mapping validation failed - 1 error(s), 0 warning(s)
Altova_Hierarchical: JSON components are not supported for Java.
The output component Altova_Hierarchical has no output file name set. A default file name will be used.
The second thing, that is important for me, is capabilities to create graphic mapping between JSON and XML like example below shows:
Thanks for the reply.
There is underscore-java library with static method U.xmlToJson(xml). I am the maintainer of the project.
<anyxml>data</anyxml>
Output:
{
"anyxml": "data",
"#omit-xml-declaration": "yes"
}

Saxon-HE Integrated Extension Functions

I should have originally posted my question by stating that our code was using an embedded saxon extension function - saxon:parse($xml) which returned the root element/node of the xml. However, in Saxon-HE that extension is no longer available - so I am trying to write an Integrated extension that parses an xml string into a document and returns the root element.
I am using Saxon-HE 9.5.1.6 - I am trying to write an Integrated Extension Function that returns the ROOT Node of a Document. The function receives an xml string - creates a document and needs to return the root node to the xslt for it to then use xpath to find a specific element. The call() method of the ExtensionFunctionCall class/types return a Sequence type - how do I return a NodeSequence or NodeType? How do I construct the NodeSequence from my Document?
I can step and debug and confirm the function receives the correct xml - parses this into a document, but so far I am unable to determine how to construct the NodeSequence with my RootElement.
I have other Integrated Extension Functions that return a StringValue - and those work great, but I can't glean from the class methods available how to return anything other than simple (numerica/alpha/item) types from the ExtensionFunctionCall
Thank you.
The class DocumentInfo implements Sequence, so if you return a DocumentInfo, that will satisfy the interface. You can construct a DocumentInfo using
context.getConfiguration().buildDocument()
If you want to construct your document using some external object model such as DOM or JDOM2, you will need to take the root node of that external document and wrap it in the appropriate kind of Saxon DocumentWrapper to make it into a DocumentInfo.
For anyone reading - following this I was able to get this working with Michael Kay's help - my solution is the following:
Source source = new StreamSource(new StringReader(myXMLparam));
DocumentInfo docInfo = context.getConfiguration().buildDocument(source);
return docInfo;

Categories

Resources