Assign Json to a string without serilization in c#

huangapple go评论81阅读模式
英文:

Assign Json to a string without serilization in c#

问题

我有一个JSON字符串

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

我希望将其分配给这种类型的对象

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

换句话说,我需要将JSON转换为对象,但内部对象应分配为JSON字符串。

英文:

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

答案1

得分: 1

以下是代码的中文翻译:

最简单的方式是:

var jObj = JObject.Parse(json);

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

或者,如果您不想要缩进格式:

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

或者,如果您喜欢更复杂的方式:

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"]
        };
    }

    // 或者也可以这样写
    // 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));
    }
}

或者,如果您有许多属性应该以常规方式反序列化:

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);
    }
}

注意:此翻译仅包括代码部分,不包括问题或其他内容。

英文:

the simpliest way is

	var jObj = JObject.Parse(json);

	MyType myType = new MyType
	{
		F1 = jObj[&quot;F1&quot;].ToString(),
		F2 = jObj[&quot;F2&quot;].ToString()
	};

or if you don't want indented formating

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

of if you like a hard way

MyType myType = JsonConvert.DeserializeObject&lt;MyType&gt;(json,new MyTypeJsonConverter());

public class MyTypeJsonConverter : JsonConverter&lt;MyType&gt;
{
	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[&quot;F1&quot;]),
			F2 = (string)jObj[&quot;F2&quot;]
		};
	}

    // or maybe this 
    // public override bool CanWrite =&gt; 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&lt;MyType&gt;(json);

public class MyType
{ 
   [JsonConverter(typeof(MyTypePropertyJsonConverter))]
	public string F1 { get; set; }
	
	public string F2 { get; set; }
}

public class MyTypePropertyJsonConverter : JsonConverter&lt;string&gt;
{
	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);
	}
}

答案2

得分: 1

The translated code portion is:

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);

Please note that I have removed the code comments for translation simplicity.

英文:

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&lt;dynamic&gt;(json);
MyType myType = new MyType();
myType.F1 = jsonElement.GetProperty(&quot;F1&quot;).ToString();
myType.F2 = jsonElement.GetProperty(&quot;F2&quot;).ToString();		
Console.WriteLine(myType.F1 + &quot;, &quot; + myType.F2);

I hope it may help you some way.

huangapple
  • 本文由 发表于 2023年4月13日 18:59:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定