How to specify Namespace with Jackson XmlMapper() - jackson

I have a POJO that I need to parse to XML. I'm using Jackson 2.10.
I pass my Object and parse as follows:
ObjectMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
byte[] val = mapper.writeValueAsBytes(infoToPost);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(infoToPost));
My output has xmlns:wstxnsl. I would like to have it be xmlns:xsi followed by the xsi:type"".
I believe this is because woodstox is used as default. I need to change it.
What do i need to do to make this happen with Jackson?
Desired Output:
<network_object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="subnetNetworkObjectDTO">
Actual Output
<wstxns1:network_objects xmlns:wstxns1="http://www.w3.org/2001/XMLSchema-instance">

Related

Get specific data from protobuf's message

I understand probuffer as a kind of serialization like JSON. I try to parse and extract GeneratedMessageV3 data(generated by probuf) in Java.
public final class ProtoBufMessage extends GeneratedMessageV3 implements ProductJoinOrBuilder {
/*Some kind of code autogenerated by protoc*/
}
In case of JSON, there is JsonPointer to extract specific data. As we know, we can use JsonPointer just defining the path of the data we want to extract.
JsonPointer jsonPointer = Json.createPointer("/books/1");
Is there any way to extract specific data from protobuf's message just like JsonPointer?
Or is there any official api do same job??

Gson api parsing issue Kotlin

I'm trying to parse the JSON returned by the following API call (recipe and ingredientLines only):
https://api.edamam.com/search?q=khachapuri&app_id=xxx&app_key=yyy
My model for GSON looks like this:
class FoodModel {
var label:String = "Yummy"
var image:String = "https://agenda.ge/files/khachapuri.jpg"
var ingredientLines = ""
}
After launching the app, I'm facing the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
I think I'm writing the model class incorrectly, because the structure of a json is not clear for me. This is how I'm trying to use Gson: val foodItems = Gson().fromJson(response, Array<FoodModel>::class.java) can anyone help?
The JSON object returned by the API has a slightly different structure compared to your model.
In particular the API is returning a complex object that you need to traverse in order to extract the information you are interest into. A high-level example (I'm not able to test it, but hopefully you'll get the gist of it):
data class Response(
val hits: List<Hit>
)
data class Hit(
val recipe: Recipe
)
data class Recipe(
val label: String,
val image: String
)
val foodItems = Gson().fromJson(response, Response::class.java)
Just be aware that Gson may create instances in an unsafe manner, which means you may experience NullPointerExceptions thrown apparently with no reason. If you want to prove it, just rename image to anything else (you can also try with other fields, it doesn't matter), and you'll see its value is null even if the type is non-nullable.

org.apache.avro.SchemaParseException: Can't redefine: org.apache.avro.reflect.Pair620b9c15f622a7

I have a class as given below
class A
{
private Map<Long ,Set<Long>> x;
private Map<Long ,Set<Long>> y;}
When avro tries to create schema using reflection it creates the schema having the name of the map as Pair620b9c15f622a7 for both the fields. ANd hence I get the exception
Schema s = ReflectData.get().getSchema(A.class);
I am not sure as of why I am getting this error , though the field names are completely different.
1 solution for this might be to explicitly define the name of x and y in the schema using #AvroSchema annotation, but that is very manual task and I have to do it for all such mappings in my code
pretty similar to what I just answered here Generate Avro file based on java file. TRy using kite sdk util class

One to many mapping in mule data mapper

I have an input xml and it has only one Telephone child element,
<ContactMethod>
<Telephone type="fax">
<Number>String</Number>
<Extension>String</Extension>
</Telephone>
</ContactMethod>
But my output XML has multiple Telephone child element,
<ContactMethod>
<Telephone type="fax">
<Number>String</Number>
<Extension>String</Extension>
</Telephone>
<Telephone type="fax">
<Number>String</Number>
<Extension>String</Extension>
</Telephone>
</ContactMethod>
I want to map from input element Number to output Number and also Extension element.
I can't change the schema because it is globally used.
I don't see any options to map using Element Mapping.
And I tried using adding Rule to the ContactMethod element, but no luck.
......
Above I is just example I asked. I need one to many mapping idea in datamapper.
See attached image, that is my actual requirement. Look at the Disclosure/CandidateDisclosure elements in source and destination
My source is XML and target is JSON, but the actual logic I need is similar for all the structures ..
I am maintaining a project which use DataMapper and faced the same issue. To solve it I add Java Transformer (you can use Groovy or other scripting languages) after DataMapper to group the one-to-many relationship.
Following is the pseudo code:
provide empty telpMap
foreach telpXml which is extracted from src/payload {
key = telpXml.get("#type");
if (telpMap.containsKey(key)) {
List number = telpMap.get(key).get("Number");
number.addAll(telpXml.get("Number"));
List extension = telpMap.get(key).get("Extension");
extension.addAll(telpXml.get("Extension"));
} else {
telpMap.put(key, telpXml);
}
}
return telpMap.values();

ServiceStack Serializing lists in XML

I have a predefined xml sample which defines the requests and responses, the only part I can't get working with ServiceStack.Text.XmlSerializer is the following snippet, which is basically a list of strings.
<user>
....
<EmailPreferences>
<EmailProgram>Newsletter</EmailProgram>
<EmailProgram>Coupons</EmailProgram>
</EmailPreferences>
I tried using the example Using Structs to customise JSON, but as the title implies that didn't affect the xml serialisation.
ServiceStack uses .NET's XML DataContractSerializer under the hood. So you can decorate the models with any customizations it support. So to get something like the above you could do:
[CollectionDataContract(Name="EmailPreferences", ItemName="EmailProgram")]
public class EmailPreferences : List<string>
{
public EmailPreferences() { }
public EmailPreferences(IEnumerable<string> collection) : base(collection){}
}
Global XML Namespaces
Although you can individually add namespaces to each DataContract a better idea instead is to have all your DTOs share the same namespace, this will prevent the auto-generated and repeating namespaces from appearing in your XML.
As the ResponseStatus DTO is already under http://schemas.servicestack.net/types namespace so if you don't care what your namespace is I would leave it at that.
The easiest way to have all your DataContract's under the same namespace is to put these assembly wide attributes in your AssemblyInfo.cs for each C# namespace your DTOs are in:
[assembly: ContractNamespace("http://schemas.servicestack.net/types",
ClrNamespace = "ServiceStack.Examples.ServiceModel.Operations")]
[assembly: ContractNamespace("http://schemas.servicestack.net/types",
ClrNamespace = "ServiceStack.Examples.ServiceModel.Types")]