将类属性转换为[JsonPropertyName,Value]数组

时间:2016-08-15 09:59:20

标签: c# json json.net

无论如何都要使用一些C#类并将每个属性转换为[JsonPropertyName,value]的字符串数组,而不通过字符串创建JSON。我一直在尝试使用newtonsoft.Json将对象序列化为JSON,但我无法以与所需输出相同的方式显示属性。

public class UserCredentials
{
    [JsonProperty("InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Username")]
    public string Username;

    [JsonProperty("InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Password")]
    public string Password;
}

所需的JSON输出:

{"name":"setParameterValues", 
    "parameterValues": [
        ["InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Username", "tester@test.net"],
        ["InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Password", "hello"]
    ]
}

3 个答案:

答案 0 :(得分:1)

您可以创建自定义JSON序列化程序。有关示例,请查看这些链接(link1link2)。

以下是您的代码的外观(它只是草稿,您必须正确使用反射):

    private class PropertyNamesSerializer : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteValue("setParameterValues");
            writer.WritePropertyName("parameterValues");
            writer.WriteStartArray();
            writer.WriteStartObject();
            foreach (var property in value.GetType().GetProperties())
            {
                var attribute = property.GetCustomAttribute<JsonPropertyAttribute>();
                writer.WritePropertyName(attribute.PropertyName);
                writer.WriteValue(property.GetValue(value));
            }
            writer.WriteEndObject();
            writer.WriteEndArray();
            writer.WriteEndObject();
        }
    // other methods

用法:

    [JsonConverter(typeof(PropertyNamesSerializer))]
    public class UserCredentials
    {
        [JsonProperty("InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Username")]
        public string Username { get; set; }

        [JsonProperty("InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.Password")]
        public string Password { get; set; }
    }

    private static void Main(string[] args)
    {

        Console.WriteLine(JsonConvert.SerializeObject(new UserCredentials() {Username = "test", Password = "something"}));
    }

答案 1 :(得分:0)

您可以将对象转换为属性数组,然后将其序列化。 像这样:

public class Test
{
    [JsonProperty("TestJsonString")]
    public string TestFieldString { get; set; }

    [JsonProperty("TestJsonInt")]
    public int TestFieldInt { get; set; }

    public int TestFieldInt2 { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var data = new Test() {TestFieldInt = 1, TestFieldString = "11"};
        var testArray = data.GetType().GetProperties()
            .Where(x => x.GetCustomAttributes(true).Any(attr => attr is JsonPropertyAttribute))
            .Select(x => new []
            {
                (x.GetCustomAttributes(typeof(JsonPropertyAttribute), true).Single() as JsonPropertyAttribute).PropertyName,
                x.GetGetMethod().Invoke(data, null) == null ? "" : x.GetGetMethod().Invoke(data, null).ToString()
            });
        var serialized = JsonConvert.SerializeObject(testArray);
    }
}

答案 2 :(得分:0)

您可以拥有JSON属性和问题中提到的值,根据我的理解,使用Newtonsoft.Json如下所示,

string x = JsonConvert.SerializeObject([YourObject],Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead} );