Skip to content

Type that can not be created from itself is not automatically mapped. in v10 #911

@DocSvartz

Description

@DocSvartz

We have encountered quite unwanted behavior with Mapster v.10.0.6 which was not present in v.7.4.0.

When I try to map classes with certain property types, it throws an error. So far I have found the following types that cause the following exceptions in v.10.0.6:

JsonDocument:

Unhandled exception. Mapster.CompileException: Error while compiling
source=SourceClassWithJsonDocument
destination=DestinationClassWithJsonDocument
type=Map
 ---> Mapster.CompileException: Error while compiling
source=System.Text.Json.JsonDocument
destination=System.Text.Json.JsonDocument
type=Map
 ---> System.InvalidOperationException: No default constructor for type 'JsonDocument', please use 'ConstructUsing' or 'MapWith'

Uri:

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')
   at System.ArgumentNullException.Throw(String paramName)
   at lambda_method1(Closure, Object)
   at Mapster.TypeAdapter.Adapt[TDestination](Object source, TypeAdapterConfig config)
   at Mapster.TypeAdapter.Adapt[TDestination](Object source)

It can be reproduced with the following code:

using System.Text.Json;
using Mapster;

var jsonSource = new SourceClassWithJsonDocument
{
    Json = JsonDocument.Parse("{\"key\": \"value\"}")
};

var jsonDest = jsonSource.Adapt<DestinationClassWithJsonDocument>();
Console.WriteLine(jsonDest.Json.RootElement.GetProperty("key").GetString());

var uriSource = new SourceClassWithUri
{
    Uri = new Uri("https://www.google.com/")
};

var uriDest = uriSource.Adapt<DestinationClassWithUri>();
Console.WriteLine(uriDest.Uri);

class SourceClassWithJsonDocument
{
    public required JsonDocument Json { get; init; }
}

class DestinationClassWithJsonDocument
{
    public required JsonDocument Json { get; init; }
}

class SourceClassWithUri
{
    public required Uri Uri { get; init; }
}

class DestinationClassWithUri
{
    public required Uri Uri { get; init; }
}

Downgrading the Mapster version to v.7.4.0 eliminates the problem.

It also can be fixed with the mapping rules, like:

TypeAdapterConfig<JsonDocument, JsonDocument>.NewConfig().MapWith(src => src);
TypeAdapterConfig<Uri, Uri>.NewConfig().MapWith(src => src);

, but due to the nature of specifying every type in quite large codebase this workaround is not preferred.

Is there any way to fix it without downgrading?

Originally posted by @anaruzhnii in #883

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions