C#对象将属性值转换为json对象

时间:2018-12-05 21:55:10

标签: c# json

我有一个C#对象,我需要将其属性值放入自己的json对象中。我正在努力如何动态地做到这一点。我的C#类中有具有值的属性,我需要分别将这些属性值设为json中的“键/值”对。

public class TransHelper
{
    public string Key { get; set; }
    public string Translation { get; set; }
}
TransHelper j = new TransHelper { Key = "MyKeyValue", 
                                  Translation = "MyTranslationValue" }; 
// Need to be json like this
// json { MyKeyValue: MyTranslationValue }

如何使属性值插入到新对象中,其中j.Key值是新的Key,j.Translation是新值?我可以在那里使用newtonsoft或任何json库,我确定这里缺少一些简单的东西。

5 个答案:

答案 0 :(得分:1)

我要执行此操作的方法是实现自定义JsonConverterdoc)。

SO上有this question,可以提供有关执行方法的更多详细信息。

这里是执行此操作的一种方法:

public class TransHelperConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var transHelperInst = value as TransHelper;

        if(transHelperInst is null)
             throw new ArgumentException();

        //  Creates the Json property. 
            var property = new JProperty(transHelperInst.Key, transHelperInst.Translation);

        //  Adds it the Json object.
        var transHelperObject = new JObject();
        transHelperObject.AddFirst(property);

        //  Writes the object.
        transHelperObject.WriteTo(writer);
   }

   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
       throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
   }

  public override bool CanRead => false;

  public override bool CanConvert(Type objectType)
  {
      return objectType == typeof(TransHelper);
  }
}

现在,您可以像这样使用此转换器:

var serializedValue = JsonConvert.SerializeObject(new TransHelper {Key = "MyKeyValue", Translation = "MyTranslationValue"}, Formatting.Indented, new TransHelperConverter());

这将为您提供以下结果:

{
  "MyKeyValue": "MyTranslationValue"
}

答案 1 :(得分:1)

我认为您可以实现Json.NET类的通用抽象JsonConverter来实现这一目标。

这是转换器的实现:

public class MySerializer : JsonConverter<TransHelper>
{
    public override TransHelper ReadJson(JsonReader reader, Type objectType, TransHelper existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, TransHelper value, JsonSerializer serializer)
    {
        if(value == null) return;
        writer.WritePropertyName(value.Key);
        writer.WriteValue(value.Translation);
    }
}

这是您的称呼方式:

var j = new TransHelper
{
    Key = "MyKeyValue",
    Translation = "MyTranslationValue"
};

var jsonString = JsonConvert.SerializeObject(j, Newtonsoft.Json.Formatting.Indented, new MySerializer());

答案 2 :(得分:1)

public class TransHelper
{
    public string Key { get; set; }
    public string Translation { get; set; }
}

public static void Main()
{
    var myList = new List<TransHelper> {
        new TransHelper { Key = "K1", Translation = "T1" },
        new TransHelper { Key = "K2", Translation = "T2" },
        new TransHelper { Key = "K3", Translation = "T3" }
    };

    var dict = myList.ToDictionary(t => t.Key, t => t.Translation);
    //Serialize dict to Json using Newtonsoft.Json (JSON.Net) or Utf8Json libraries
}

答案 3 :(得分:1)

最好将Dictionary之类的容器与<Key, Value>一起使用,然后可以使用Newtonsoft.Json(比JavaScriptSerializer更好),代码如下所示:

JsonConvert.SerializeObject(dict);

示例:

var foo = new Dictionary<string, string>();

foo.Add("key1", "value1");
foo.Add("key2", "value2");
foo.Add("key3", "value3");
foo.Add("key4", "value4");

Console.WriteLine(JsonConvert.SerializeObject(foo));
// outputs { "key1":"value1","key2":"value2","key3":"value3","key4":"value4"}

答案 4 :(得分:1)

这是一个应该完成此操作的自定义转换器(假设您使用的是Newtonsoft Json.Net):

using System;
using Newtonsoft.Json;

namespace ConsoleApp8
{

  public class TransHelper
  {
    public string Key { get; set; }
    public string Translation { get; set; }
  }

  public class MyBlob
  {
    public string Foo { get; set; }
    public TransHelper Bar { get; set; }
  }

  public class TransHelperConverter : JsonConverter<TransHelper>
  {

    public override TransHelper ReadJson( JsonReader reader, Type objectType, TransHelper existingValue, bool hasExistingValue, JsonSerializer serializer )
    {
      string key = null;
      string val = null;
      TransHelper instance = null;

      if ( reader.TokenType != JsonToken.Null )
      {
        if ( reader.TokenType != JsonToken.StartObject )
          throw new JsonReaderException( $"Unexpected Token: ${reader.TokenType}" );

        if ( !reader.Read() )
          throw new JsonReaderException( $"Unexpected EOF in Json" );

        if ( reader.TokenType != JsonToken.EndObject )
        {
          if ( reader.TokenType != JsonToken.PropertyName )
            throw new JsonReaderException( $"Unexpected Token: ${reader.TokenType}" );

          key = (string)reader.Value;
          if ( !reader.Read() )
            throw new JsonReaderException( $"Unexpected EOF in Json" );

          if ( reader.TokenType != JsonToken.String )
            throw new JsonReaderException( $"Unexpected Token: ${reader.TokenType}" );

          val = (string)reader.Value;
          if ( !reader.Read() )
            throw new JsonReaderException( "Unexpected EOF in Json" );

        }

        if ( reader.TokenType != JsonToken.EndObject )
          throw new JsonReaderException( $"Unexpected Token: ${reader.TokenType}" );

        instance = new TransHelper
        {
          Key = key,
          Translation = val,
        };

      }

      return instance;
    }

    public override void WriteJson( JsonWriter writer, TransHelper value, JsonSerializer serializer )
    {

      writer.WriteStartObject();
      writer.WritePropertyName( value.Key );
      writer.WriteValue( value.Translation );
      writer.WriteEndObject();

      return;

    }

  }

  class Program
  {

    static void Main( string[] argv )
    {
      string json = @"
{
  ""Foo"": ""foo-value"",
  ""Bar"": {
    ""source"": ""translated-value""
  },
}".Trim();

      TransHelperConverter converter = new TransHelperConverter();
      MyBlob deserialized = JsonConvert.DeserializeObject<MyBlob>( json, converter );
      string reserialized = JsonConvert.SerializeObject( deserialized, Formatting.Indented, converter );

      return;
    }

  }

}