Home > Net >  How to convert object to Json in .net core 6 JsonConverter
How to convert object to Json in .net core 6 JsonConverter

Time:02-04

Im trying to convert a object that looks like the object below into Json in .net core 6?

{{
  "Id": "178",
  "DisplayName": "Jon Doe",
  "Email": "[email protected]",
  "FullName": "Jon Doe",
  "UserName": "jdoe"
}}

Before upgrading to .net core 6 the object would automatically get converted to json and sent to the backend in the proper format. Without any converters it gets sent back as an empty [].

The route im currently trying is using JsonConverter in my Program.cs file but not sure if this route makes sense.

public class DataObjectConverter : System.Text.Json.Serialization.JsonConverter<Object>
{

    public override void Write(Utf8JsonWriter writer, Object value, JsonSerializerOptions options)
    {
       //doesnt work 
        writer.WriteStringValue(value.ToString());
    }
}

The source value looks like below, but I convert it to the deserialized version above with this code. When I try to serialize it back is were the problem happens.

var deserializeSourceData = JsonConvert.DeserializeObject<JObject>(sourceData)

Source looks like this

"{\"Id\":\"178\",\"DisplayName\":\"Jon Doe\",\"Email\":\"[email protected]\",\"FullName\":\"Jon Doe\",\"UserName\":\"jdoe\"}"

Json Serializer returns empty []

var serializerSourceData = System.Text.Json.JsonSerializer.Serialize(deserializeSourceData)

serializerSourceData looks like this

{"Id":[],"DisplayName":[],"Email":[],"FullName":[],"UserName":[]}

Any ideas how to get this desired format?

{ 
  DisplayName: "Jon Doe"
  Email: "[email protected]"
  FullName: "Jon Doe"
  Id: "178"
  UserName: "jdoe"
}

CodePudding user response:

you are mixing in one bottle Newtonsoft.Json and System.Text.Json serializers. JObject and JsonObject are completely different classes. You will have to select something one

Newtonsoft.Json

using Newtonsoft.Json;

string sourceData="{\"Id\":\"178\",\"DisplayName\":\"Jon Doe\",\"Email\":\"[email protected]\",\"FullName\":\"Jon Doe\",\"UserName\":\"jdoe\"}";
    
JObject deserializeSourceData = JsonConvert.DeserializeObject<JObject>(sourceData);

//or this syntax is more clear and shorter
deserializeSourceData = JObject.Parse(sourceData);
     
sourceData = JsonConvert.SerializeObject(deserializeSourceData);

//or this syntax is more clear and shorter
sourceData = deserializeSourceData.ToString();

Now System.Text.Json

using System.Text.Json;

 JsonObject deserializeSourceData1 = System.Text.Json.JsonSerializer.Deserialize<JsonObject>(sourceData);
     
sourceData = System.Text.Json.JsonSerializer.Serialize(deserializeSourceData1);

if you want to convert JObject to JsonObject, you can serialize a JObject to a json string, and after this deserialize the json string to a JsonObject.

  • Related