skip to Main Content

I have a JSON string

{
  "F1":
  { 
    "BF1":"BV1",
    "BF2":"BV2"
  },
  "F2":"BF1"
}

and I wish to assign it to an object of this type

public class MyType
{
   public string F1 {get;set;} 
   public string F2 {get;set;}
}

in other words, I need to convert JSON to an object, but the inner object is to be assigned as a JSON string

2

Answers


  1. the simpliest way is

        var jObj = JObject.Parse(json);
    
        MyType myType = new MyType
        {
            F1 = jObj["F1"].ToString(),
            F2 = jObj["F2"].ToString()
        };
    

    or if you don’t want indented formating

    MyType myType = new MyType
        {
            F1 = JsonConvert.SerializeObject(jObj["F1"]),
            F2 = (string) jObj["F2"];
        };
    

    of if you like a hard way

    MyType myType = JsonConvert.DeserializeObject<MyType>(json,new MyTypeJsonConverter());
    
    public class MyTypeJsonConverter : JsonConverter<MyType>
    {
        public override MyType ReadJson(JsonReader reader, Type objectType, MyType existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var jObj = JObject.Load(reader);
    
            return new MyType
            {
                F1 = JsonConvert.SerializeObject(jObj["F1"]),
                F2 = (string)jObj["F2"]
            };
        }
    
        // or maybe this 
        // public override bool CanWrite => false;
    
        public override void WriteJson(JsonWriter writer, MyType value, JsonSerializer serializer)
        {
            var val = new
            {
                F1 = JObject.Parse(value.F1),
                F2 = value.F2
            };
            
            writer.WriteRaw(JsonConvert.SerializeObject(val, Newtonsoft.Json.Formatting.Indented));
        }
        
    }
    

    or if you have many properties that should deserialize common way

    MyType myType = JsonConvert.DeserializeObject<MyType>(json);
    
    public class MyType
    { 
       [JsonConverter(typeof(MyTypePropertyJsonConverter))]
        public string F1 { get; set; }
        
        public string F2 { get; set; }
    }
    
    public class MyTypePropertyJsonConverter : JsonConverter<string>
    {
        public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            return JsonConvert.SerializeObject(JToken.Load(reader));
        }
    
        public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
        {
            writer.WriteRawValue(value);
        }
    }
    
    Login or Signup to reply.
  2. Though the answer posted by @serge looks best to me. But I spent some time to resolve your issue and I ended up with the below code:

    dynamic jsonElement = JsonSerializer.Deserialize<dynamic>(json);
    MyType myType = new MyType();
    myType.F1 = jsonElement.GetProperty("F1").ToString();
    myType.F2 = jsonElement.GetProperty("F2").ToString();       
    Console.WriteLine(myType.F1 + ", " + myType.F2);
    

    I hope it may help you some way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search