Unrecognized selector: [NSSQLToMany _setInverseManyToMany:] - objective-c

This is the strangest error I've ever had, simply because I can't find any information on it anywhere.
Background:
I have an app using RestKit (current master) that maps to Core Data. I'm using a custom mapping provider (subclass of RKObjectMappingProvider). This generates all of the mappings that I need, similar to the RKGithub project.
Some of my objects have many-to-many relationships, so I have to register some of the relationships (in the mapping provider) after the others are set up to avoid an infinite recursion. (Friends has_many Friends has_many Friends...)
When the app runs and RestKit configures itself, an error occurs on this line (in RKManagedObjectStore.m)
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];
I can't step into the "initWithManagedObjectModel:" method. The only information I get is this exception in the logs:
-[NSSQLToMany _setInverseManyToMany:]: unrecognized selector sent to instance 0xcc78890
I have no idea what caused this or how to fix it. I can't find any documentation on it or even anyone who's had this problem before. All I could find was this dump of the iOS framework:
public struct NSSQLManyToMany : IEquatable<NSSQLManyToMany> {
internal NObjective.RuntimeObject Handle;
public static readonly RuntimeClass ClassHandle = CoreDataCachedClasses.NSSQLManyToMany;
public static implicit operator IntPtr( NSSQLManyToMany value ) {
return value.Handle;
}
public static implicit operator NObjective.RuntimeObject( NSSQLManyToMany value ) {
return value.Handle;
}
public override bool Equals( object value ) {
var compareTo = value as NSSQLManyToMany?;
return compareTo != null && Handle == compareTo.Value.Handle;
}
public bool Equals( NSSQLManyToMany value ) {
return Handle == value.Handle;
}
public static bool operator ==( NSSQLManyToMany value1, NSSQLManyToMany value2 ) {
return value1.Handle == value2.Handle;
}
public static bool operator !=( NSSQLManyToMany value1, NSSQLManyToMany value2 ) {
return value1.Handle != value2.Handle;
}
public NSSQLManyToMany( IntPtr value ) {
this.Handle = new RuntimeObject( value );
}
public static NSSQLManyToMany alloc() {
return new NSSQLManyToMany( ClassHandle.InvokeIntPtr( Selectors.alloc ) );
}
unsafe public NObjective.RuntimeObject inverseColumnName() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.inverseColumnName( Handle, CachedSelectors.inverseColumnName, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return new NObjective.RuntimeObject( ___result );
}
unsafe public NObjective.RuntimeObject inverseManyToMany() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.inverseManyToMany( Handle, CachedSelectors.inverseManyToMany, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return new NObjective.RuntimeObject( ___result );
}
unsafe public bool isMaster() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.isMaster( Handle, CachedSelectors.isMaster, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return ___result;
}
unsafe public bool isReflexive() {
RuntimeObject ___occuredException;
var ___result = NativeMethods.isReflexive( Handle, CachedSelectors.isReflexive, out ___occuredException, 0 );
if( ___occuredException != RuntimeObject.Null ) throw RuntimeException.Create( ___occuredException );
return ___result;
}
private static class NativeMethods {
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern IntPtr inverseColumnName( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern IntPtr inverseManyToMany( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern bool isMaster( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
[DllImport(Runtime.InteropLibrary, EntryPoint = "objc_msgSend_eh2")]
public static extern bool isReflexive( RuntimeObject ___object, Selector ___selector, out RuntimeObject ___occuredException, int ___stackSize );
}
static internal class CachedSelectors {
public static readonly Selector inverseColumnName = "inverseColumnName";
public static readonly Selector inverseManyToMany = "inverseManyToMany";
public static readonly Selector isMaster = "isMaster";
public static readonly Selector isReflexive = "isReflexive";
}
}
Which very clearly seems to have a setter:
public NSSQLManyToMany( IntPtr value ) {
this.Handle = new RuntimeObject( value );
}
Any ideas?
EDIT:
I should add that I've tried all of the "simple" solutions. Deleting the app from the sim doesn't work.
I suspect that it might be because I have an entity that has two "has and belongs to many" relationships with the same (different) entity. But I can't see why that would be an actual problem.

Just figured this out!
I had two relationships on one entity pointing to another entity, and they inadvertently had the same inverse.
To illustrate:
Part:
has many (Car*)cars, inverse parts
has one (Car*)deliveryTruck, inverse parts
A bit contrived, but the idea is there. I had to change the second parts to some other property.
Hopefully this will help someone else with the same cryptic error message. You'd expect clang to warn you about something like this! (It freaks out enough as it is if you don't have an inverse at all).

Related

HTTP end point property string starts with "is" will get omit [duplicate]

This might be a duplicate. But I cannot find a solution to my Problem.
I have a class
public class MyResponse implements Serializable {
private boolean isSuccess;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Getters and setters are generated by Eclipse.
In another class, I set the value to true, and write it as a JSON string.
System.out.println(new ObjectMapper().writeValueAsString(myResponse));
In JSON, the key is coming as {"success": true}.
I want the key as isSuccess itself. Is Jackson using the setter method while serializing? How do I make the key the field name itself?
This is a slightly late answer, but may be useful for anyone else coming to this page.
A simple solution to changing the name that Jackson will use for when serializing to JSON is to use the #JsonProperty annotation, so your example would become:
public class MyResponse implements Serializable {
private boolean isSuccess;
#JsonProperty(value="isSuccess")
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
This would then be serialised to JSON as {"isSuccess":true}, but has the advantage of not having to modify your getter method name.
Note that in this case you could also write the annotation as #JsonProperty("isSuccess") as it only has the single value element
I recently ran into this issue and this is what I found. Jackson will inspect any class that you pass to it for getters and setters, and use those methods for serialization and deserialization. What follows "get", "is" and "set" in those methods will be used as the key for the JSON field ("isValid" for getIsValid and setIsValid).
public class JacksonExample {
private boolean isValid = false;
public boolean getIsValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
}
Similarly "isSuccess" will become "success", unless renamed to "isIsSuccess" or "getIsSuccess"
Read more here: http://www.citrine.io/blog/2015/5/20/jackson-json-processor
Using both annotations below, forces the output JSON to include is_xxx:
#get:JsonProperty("is_something")
#param:JsonProperty("is_something")
When you are using Kotlin and data classes:
data class Dto(
#get:JsonProperty("isSuccess") val isSuccess: Boolean
)
You might need to add #param:JsonProperty("isSuccess") if you are going to deserialize JSON as well.
EDIT: If you are using swagger-annotations to generate documentation, the property will be marked as readOnly when using #get:JsonProperty. In order to solve this, you can do:
#JsonAutoDetect(isGetterVisibility = JsonAutoDetect.Visibility.NONE)
data class Dto(
#field:JsonProperty(value = "isSuccess") val isSuccess: Boolean
)
You can configure your ObjectMapper as follows:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
&& method.getName().startsWith("is")) {
return method.getName();
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
I didn't want to mess with some custom naming strategies, nor re-creating some accessors.
The less code, the happier I am.
This did the trick for us :
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonIgnoreProperties({"success", "deleted"}) // <- Prevents serialization duplicates
public class MyResponse {
private String id;
private #JsonProperty("isSuccess") boolean isSuccess; // <- Forces field name
private #JsonProperty("isDeleted") boolean isDeleted;
}
Building upon Utkarsh's answer..
Getter names minus get/is is used as the JSON name.
public class Example{
private String radcliffe;
public getHarryPotter(){
return radcliffe;
}
}
is stored as { "harryPotter" : "whateverYouGaveHere" }
For Deserialization, Jackson checks against both the setter and the field name.
For the Json String { "word1" : "example" }, both the below are valid.
public class Example{
private String word1;
public setword2( String pqr){
this.word1 = pqr;
}
}
public class Example2{
private String word2;
public setWord1(String pqr){
this.word2 = pqr ;
}
}
A more interesting question is which order Jackson considers for deserialization. If i try to deserialize { "word1" : "myName" } with
public class Example3{
private String word1;
private String word2;
public setWord1( String parameter){
this.word2 = parameter ;
}
}
I did not test the above case, but it would be interesting to see the values of word1 & word2 ...
Note: I used drastically different names to emphasize which fields are required to be same.
You can change primitive boolean to java.lang.Boolean (+ use #JsonPropery)
#JsonProperty("isA")
private Boolean isA = false;
public Boolean getA() {
return this.isA;
}
public void setA(Boolean a) {
this.isA = a;
}
Worked excellent for me.
If you are interested in handling 3rd party classes not under your control (like #edmundpie mentioned in a comment) then you add Mixin classes to your ObjectMapper where the property/field names should match the ones from your 3rd party class:
public class MyStack32270422 {
public static void main(String[] args) {
ObjectMapper om3rdParty = new ObjectMapper();
om3rdParty .addMixIn(My3rdPartyResponse.class, MixinMyResponse.class);
// add further mixins if required
String jsonString = om3rdParty.writeValueAsString(new My3rdPartyResponse());
System.out.println(jsonString);
}
}
class MixinMyResponse {
// add all jackson annotations here you want to be used when handling My3rdPartyResponse classes
#JsonProperty("isSuccess")
private boolean isSuccess;
}
class My3rdPartyResponse{
private boolean isSuccess = true;
// getter and setter here if desired
}
Basically you add all your Jackson annotations to your Mixin classes as if you would own the class. In my opinion quite a nice solution as you don't have to mess around with checking method names starting with "is.." and so on.
there is another method for this problem.
just define a new sub-class extends PropertyNamingStrategy and pass it to ObjectMapper instance.
here is a code snippet may be help more:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
String input = defaultName;
if(method.getName().startsWith("is")){
input = method.getName();
}
//copy from LowerCaseWithUnderscoresStrategy
if (input == null) return input; // garbage in, garbage out
int length = input.length();
StringBuilder result = new StringBuilder(length * 2);
int resultLength = 0;
boolean wasPrevTranslated = false;
for (int i = 0; i < length; i++)
{
char c = input.charAt(i);
if (i > 0 || c != '_') // skip first starting underscore
{
if (Character.isUpperCase(c))
{
if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '_')
{
result.append('_');
resultLength++;
}
c = Character.toLowerCase(c);
wasPrevTranslated = true;
}
else
{
wasPrevTranslated = false;
}
result.append(c);
resultLength++;
}
}
return resultLength > 0 ? result.toString() : input;
}
});
The accepted answer won't work for my case.
In my case, the class is not owned by me. The problematic class comes from 3rd party dependencies, so I can't just add #JsonProperty annotation in it.
To solve it, inspired by #burak answer above, I created a custom PropertyNamingStrategy as follow:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
#Override
public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if (method.getParameterCount() == 1 &&
(method.getRawParameterType(0) == Boolean.class || method.getRawParameterType(0) == boolean.class) &&
method.getName().startsWith("set")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = "is" + method.getName().substring(3);
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
// do nothing and fall through
}
}
return super.nameForSetterMethod(config, method, defaultName);
}
#Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
&& method.getName().startsWith("is")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = method.getName();
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
// do nothing and fall through
}
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
Basically what this does is, before serializing and deserializing, it checks in the target/source class which property name is present in the class, whether it is isEnabled or enabled property.
Based on that, the mapper will serialize and deserialize to the property name that is exist.

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

Property Injection with internal setter

I have an existing application that I am modifying to use Autofac Property Injection. It seems regardless of which method I use to register my types with properties, the properties are always null unless they have public setters. With other IoC containers (e.g. Structuremap) it's possible to scope the setter internal and make it available using the InternalsVisibleTo attribute on the assembly. This would seem nice to restrict clients from modifying the assignment.
Is this possible with Autofac? Or is there another approach when working with property injection to keep the assignments secure?
I've tried using reflection with PropertiesAutoWired() as well as resolving .WithParameter() from my WebApi Global.asax - specifying the specific parameter to be set with no success as an internal setter.
[assembly: InternalsVisibleTo("MyWebAPI.dll")]
[assembly: InternalsVisibleTo("Autofac.dll")]
[assembly: InternalsVisibleTo("Autofac.Configuration.dll")]
namespace My.Namespace
{
public class BaseContext
{
public MyPublicClass _dbHelper { get; internal set; }
public BaseContext()
{
}
protected string DbConnectionString
{
get
{
return _dbHelper.DbConn; //<-Always null unless setter is public
}
}
}
}
You cannot inject internal setters with autofac, because the AutowiringPropertyInjector class is only looking for public properties (see source).
However a logic in the AutowiringPropertyInjector is very simple so you can create your own version which does injection for non public properties:
public static class AutowiringNonPublicPropertyInjector
{
public static void InjectProperties(IComponentContext context,
object instance, bool overrideSetValues)
{
if (context == null)
throw new ArgumentNullException("context");
if (instance == null)
throw new ArgumentNullException("instance");
foreach (
PropertyInfo propertyInfo in
//BindingFlags.NonPublic flag added for non public properties
instance.GetType().GetProperties(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic))
{
Type propertyType = propertyInfo.PropertyType;
if ((!propertyType.IsValueType || propertyType.IsEnum) &&
(propertyInfo.GetIndexParameters().Length == 0 &&
context.IsRegistered(propertyType)))
{
//Changed to GetAccessors(true) to return non public accessors
MethodInfo[] accessors = propertyInfo.GetAccessors(true);
if ((accessors.Length != 1 ||
!(accessors[0].ReturnType != typeof (void))) &&
(overrideSetValues || accessors.Length != 2 ||
propertyInfo.GetValue(instance, null) == null))
{
object obj = context.Resolve(propertyType);
propertyInfo.SetValue(instance, obj, null);
}
}
}
}
}
And now you can use this class in the OnActivated event
var builder = new ContainerBuilder();
builder.RegisterType<MyPublicClass>();
builder.RegisterType<BaseContext>()
.OnActivated(args =>
AutowiringNonPublicPropertyInjector
.InjectProperties(args.Context, args.Instance, true));
However the above listed solution now injects all kind of properties so even private and protected ones so you may need to extend it with some additional checks to make sure that you will only inject the properties what you would expect.
I'm using a solution like this:
builder.RegisterType<MyPublicClass>();
builder.RegisterType<BaseContext>()
.OnActivating(CustomPropertiesHandler);
With a handler like this:
//If OnActivated: Autofac.Core.IActivatedEventArgs
public void CustomPropertiesHandler<T>(Autofac.Core.IActivatingEventArgs<T> e)
{
var props = e.Instance.GetType()
.GetTypeInfo().DeclaredProperties //Also "private prop" with "public set"
.Where(pi => pi.CanWrite) //Has a set accessor.
//.Where(pi => pi.SetMethod.IsPrivate) //set accessor is private
.Where(pi => e.Context.IsRegistered(pi.PropertyType)); //Type is resolvable
foreach (var prop in props)
prop.SetValue(e.Instance, e.Context.Resolve(prop.PropertyType), null);
}
Since both IActivatingEventArgs and IActivatedEventArgs has instance and context, you might want to use wrapping methods that uses those parameters on CustomPropertiesHandler instead.
Also we can write #nemesv implementation as an extension method.
public static class AutofacExtensions
{
public static void InjectProperties(IComponentContext context, object instance, bool overrideSetValues)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
foreach (var propertyInfo in instance.GetType().GetProperties(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic))
{
var propertyType = propertyInfo.PropertyType;
if ((!propertyType.IsValueType || propertyType.IsEnum) && (propertyInfo.GetIndexParameters().Length == 0) && context.IsRegistered(propertyType))
{
var accessors = propertyInfo.GetAccessors(true);
if (((accessors.Length != 1) ||
!(accessors[0].ReturnType != typeof(void))) &&
(overrideSetValues || (accessors.Length != 2) ||
(propertyInfo.GetValue(instance, null) == null)))
{
var obj = context.Resolve(propertyType);
propertyInfo.SetValue(instance, obj, null);
}
}
}
}
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> InjectPropertiesAsAutowired<TLimit, TActivatorData, TRegistrationStyle>(
this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> registration)
{
return registration.OnActivated(args => InjectProperties(args.Context, args.Instance, true));
}
To Use;
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<StartupConfiguration>().As<IStartupConfiguration>().AsSelf().InjectPropertiesAsAutowired().AsImplementedInterfaces().SingleInstance();
}
Current version of Autofac defined optional IPropertySelector parameter for PropertiesAutowired which is used to filter out injectable properties.
default implementation for IPropertySelector is DefaultPropertySelector, which filters non public properties.
public virtual bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
if (!propertyInfo.CanWrite || propertyInfo.SetMethod?.IsPublic != true)
{
return false;
}
....
}
define custom IPropertySelector which allows injection to non public properties
public class AccessRightInvariantPropertySelector : DefaultPropertySelector
{
public AccessRightInvariantPropertySelector(bool preserveSetValues) : base(preserveSetValues)
{ }
public override bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
if (!propertyInfo.CanWrite)
{
return false;
}
if (!PreserveSetValues || !propertyInfo.CanRead)
{
return true;
}
try
{
return propertyInfo.GetValue(instance, null) == null;
}
catch
{
// Issue #799: If getting the property value throws an exception
// then assume it's set and skip it.
return false;
}
}
}
Use
builder.RegisterType<AppService>()
.AsImplementedInterfaces()
.PropertiesAutowired(new AccessRightInvariantPropertySelector(true));
Alternatively
Install
PM> Install-Package Autofac.Core.NonPublicProperty
Use
builder.RegisterType<AppService>()
.AsImplementedInterfaces()
.AutoWireNonPublicProperties();

Jackson 2.1.2 Polymorphic Deserialization throws JsonMappingException. Why?

Jackson's Polymorphic Serialize/Deserialize capability is really cool, or would be if I could figure out how to apply it to my problem at hand. There is a pretty good article at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html that I have been unable to adapt to my simplified problem.
In a nutshell, I am able to get Jackson 2.1.2 to Serialize a class hierarchy into JSON string with type information. I am unable, however, to get Jackson 2.1.2 to Deserialize that JSON String back into my class hierarchy. Below is a Unit Test that exposes this issue.
The class hierarchy is simple enough; Base Class with just two direct Subclasses. Further, the JSON output appears to respect my Jackson #JsonTypeInfo and produces a believable string from mapper.writeValueAsString
{"type":"dog","name":"King","breed":"Collie"}
But my call to mapper.readValue( jsonOfKing, Animal.class ) stacktraces with...
FAILED: testJacksonSerializeDeserialize
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class org.rekdev.fasterjacksonwtf.PolymorphismTests$Dog]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader#32b3a5a0; line: 1, column: 14]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:400)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:289)
....
Here's my unit test.
import org.testng.annotations.*;
import static org.testng.Assert.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.databind.*;
public class PolymorphismTests {
#Test
public void testJacksonSerializeDeserialize() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Animal king = new Dog();
king.name = "King";
( (Dog) king ).breed = "Collie";
String jsonOfKing = mapper.writeValueAsString( king );
// JsonMappingException right here!
Animal actualKing = mapper.readValue( jsonOfKing, Animal.class );
assertEquals( king, actualKing );
}
#JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type" )
#JsonSubTypes( { #Type( value = Cat.class, name = "cat" ), #Type( value = Dog.class, name = "dog" ) } )
abstract class Animal {
public String name;
#Override
public abstract boolean equals( Object obj );
#Override
public abstract int hashCode();
}
class Dog extends Animal {
public String breed;
#Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final Dog that = (Dog) obj;
boolean equals = name.equals( that.name ) && breed.equals( that.breed );
return equals;
}
#Override
public int hashCode() {
int hashCode = name.hashCode() + breed.hashCode();
return hashCode;
}
}
class Cat extends Animal {
public String favoriteToy;
#Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final Cat that = (Cat) obj;
boolean equals = name.equals( that.name ) && favoriteToy.equals( that.favoriteToy );
return equals;
}
#Override
public int hashCode() {
int hashCode = name.hashCode() + favoriteToy.hashCode();
return hashCode;
}
}
}
Why won't the ObjectMapper allow me to readValue process the JSON produced by the ObjectMapper.writeValue()?
Make your inner classes static, like:
static class Dog extends Animal { ... }
otherwise things will not work (since non-static inner classes require so-called "implicit this" argument to refer to an instance of enclosing class).

How to rename a component column that is a foreign key?

We are using fluentnhibernate with automapping and we have a naming convention that all columns that are foreign keys, there column name will end with "Key". So we have a convention that looks like this:
public class ForeignKeyColumnNameConvention : IReferenceConvention
{
public void Apply ( IManyToOneInstance instance )
{
// name the key field
string propertyName = instance.Property.Name;
instance.Column ( propertyName + "Key" );
}
}
This works great until we created a component in which one of its values is a foreign key. By renaming the column here it overrides the default name given to the component column which includes the ComponentPrefix which is defined in the AutomappingConfiguration. Is there a way for me to get the ComponentPrefix in this convention? or is there some other way for me to get the column name for components with a property that is a foreign key to end in the word "Key"?
After a lot of fiddling and trial & error (thus being tempted to use your solution with Reflection) I came up with the following:
This method depends on the order of the execution of the conventions. This convention-order happens via a strict hierarchy. In this example, at first, the convention of the component (IDynamicComponentConvention) is being handled and after that the conventions of the inner properties are being handled such as the References mapping (IReferenceConvention).
The strict order is where we make our strike:
We assemble the correct name of the column in the call to Apply(IDynamicComponentConvention instance), put it on the queue. Note that a Queue<T> is used which is a FIFO (first-in-first-out) collection type thus it keeps the order correctly.
Almost immediately after that, Apply(IManyToOneInstanceinstance) is called. We check if there is anything in the queue. If there is, we take it out of the queue and set it as column name. Note that you should not use Peek() instead of Dequeue() as it does not remove the object from the queue.
The code is as follows:
public sealed class CustomNamingConvention : IDynamicComponentConvention, IReferenceConvention {
private static Queue<string> ColumnNames = new Queue<string>();
public void Apply(IDynamicComponentInstance instance) {
foreach (var referenceInspector in instance.References) {
// All the information we need is right here
// But only to inspect, no editing yet :(
// Don't worry, just assemble the name and enqueue it
var name = string.Format("{0}_{1}",
instance.Name,
referenceInspector.Columns.Single().Name);
ColumnNames.Enqueue(name);
}
}
public void Apply(IManyToOneInstance instance) {
if (!ColumnNames.Any())
// Nothing in the queue? Just return then (^_^)
return;
// Set the retrieved string as the column name
var columnName = ColumnNames.Dequeue();
instance.Column(columnName);
// Pick a beer and celebrate the correct naming!
}
}
I Have figured out a way to do this using reflection to get to the underlying mapping of the IManyToOneInspector exposed by the IComponentInstance but was hoping there was a better way to do this?
Here is some example code of how I achieved this:
#region IConvention<IComponentInspector, IComponentInstance> Members
public void Apply(IComponentInstance instance)
{
foreach (var manyToOneInspector in instance.References)
{
var referenceName = string.Format("{0}_{1}_{2}{3}", instance.EntityType.Name, manyToOneInspector.Property.PropertyType.Name, _autoMappingConfiguration.GetComponentColumnPrefix(instance.Property), manyToOneInspector.Property.Name);
if(manyToOneInspector.Property.PropertyType.IsSubclassOf(typeof(LookupBase)))
{
referenceName += "Lkp";
}
manyToOneInspector.Index ( string.Format ( "{0}_FK_IDX", referenceName ) );
}
}
#endregion
public static class ManyToOneInspectorExtensions
{
public static ManyToOneMapping GetMapping(this IManyToOneInspector manyToOneInspector)
{
var fieldInfo = manyToOneInspector.GetType ().GetField( "mapping", BindingFlags.NonPublic | BindingFlags.Instance );
if (fieldInfo != null)
{
var manyToOneMapping = fieldInfo.GetValue( manyToOneInspector ) as ManyToOneMapping;
return manyToOneMapping;
}
return null;
}
public static void Index(this IManyToOneInspector manyToOneInspector, string indexName)
{
var mapping = manyToOneInspector.GetMapping ();
mapping.Index ( indexName );
}
public static void Column(this IManyToOneInspector manyToOneInspector, string columnName)
{
var mapping = manyToOneInspector.GetMapping ();
mapping.Column ( columnName );
}
public static void ForeignKey(this IManyToOneInspector manyToOneInspector, string foreignKeyName)
{
var mapping = manyToOneInspector.GetMapping();
mapping.ForeignKey ( foreignKeyName );
}
}
public static class ManyToOneMappingExtensions
{
public static void Index (this ManyToOneMapping manyToOneMapping, string indexName)
{
if (manyToOneMapping.Columns.First().IsSpecified("Index"))
return;
foreach (var column in manyToOneMapping.Columns)
{
column.Index = indexName;
}
}
public static void Column(this ManyToOneMapping manyToOneMapping, string columnName)
{
if (manyToOneMapping.Columns.UserDefined.Count() > 0)
return;
var originalColumn = manyToOneMapping.Columns.FirstOrDefault();
var column = originalColumn == null ? new ColumnMapping() : originalColumn.Clone();
column.Name = columnName;
manyToOneMapping.ClearColumns();
manyToOneMapping.AddColumn(column);
}
public static void ForeignKey(this ManyToOneMapping manyToOneMapping, string foreignKeyName)
{
if (!manyToOneMapping.IsSpecified("ForeignKey"))
manyToOneMapping.ForeignKey = foreignKeyName;
}
}