-1

I'm trying to map a JsonObject (System.Text.Json) with AutoMapper 12.0.0

Source:

public record Request
    {
        public Guid RequestId { get; set; }
        public JsonObject AdditionalParameters { get; set; }
    }

Destination:

public record ResultsEvent
{
    public Guid RequestId { get; init; }
    public JsonObject AdditionalParameters { get; init; }
}

The code which getting an error is the following:

var resultsEvent = _mapper.Map<ResultsEvent>(request);

The error I get:

---> System.InvalidOperationException: The node already has a parent.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent()
at System.Text.Json.Nodes.JsonNode.AssignParent(JsonNode parent)
at lambda_method319(Closure , Object , ResultsEvent, ResolutionContext )
--- End of inner exception stack trace ---

I saw the following answer but I wonder if there is a more elegant way than setting it manually.

Just for clarity, with NewtonSoft.Json I don't get this error.

I tried to clone it in the AutoMapper profile and serializing/deserializing but nothing worked.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    Would be great if you can provide some sample data. Thanks. – Yong Shun Mar 29 '23 at 13:04
  • 1
    Yes show something that is reproducable. So add the profile with the actual mapping and some example data. – Ralf Mar 29 '23 at 13:05
  • 1
    `CreateMap().ConvertUsing(s => s);` – Lucian Bargaoanu Mar 29 '23 at 15:13
  • Hard o say without a [mcve] showing sample JSON and how `_mapper` is constructed, but the *The node already has a parent.* exception is thrown when trying to add a `JsonNode` that already has a parent, to another parent. You may need to teach AutoMapper how to map JsonNode objects yourself. See [Clone a JsonNode and attach it to another one in .NET 6](https://stackoverflow.com/q/71570877/3744182). – dbc Mar 29 '23 at 15:13

1 Answers1

0

The more elegant way is just configure additional map for the JsonObject

expression.CreateMap<JsonObject, JsonObject>()
          .ConvertUsing(src => JsonNode.Parse(src.ToJsonString(JsonSerializerOptions.Default), 
                                              null, default)
          .AsObject());