-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.

4
  • 1
    Would be great if you can provide some sample data. Thanks. Commented Mar 29, 2023 at 13:04
  • 1
    Yes show something that is reproducable. So add the profile with the actual mapping and some example data. Commented Mar 29, 2023 at 13:05
  • 1
    CreateMap<JsonObject, JsonObject>().ConvertUsing(s => s); Commented Mar 29, 2023 at 15:13
  • Hard o say without a minimal reproducible example 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. Commented Mar 29, 2023 at 15:13

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.