将Json转换为带有转义符的字符串

时间:2018-11-20 02:05:23

标签: c# json serialization json.net

我有JSON,我需要将其转换为包含特殊字符的字符串。这是我拥有的JSON:

[{
    "job": {
        "jobName": "Flight_Test_8",
        "fields": {
            "jobGroupName": "ObjectUploader",
            "jobTemplateLibraryName": "Object_Mover_Workflows",
            "jobTemplateName": "ObjectUploader",
            "jobArgs": {
                "ObjectUploader.Source.SourceAgent": "sig_NoWhere_corxf_ny!9",
                "ObjectUploader.Source.Data": "<siglist type=\"filedir\"><el v=\"\\\\is-us-sec01-smb.com\\mxrepository\\test\\TEMP_test\" t=\"d\"></el></siglist>",
                "ObjectUploader.Target.TargetAgent": "sig-dev-lnx-01.NOWHWERE.com",
                "ObjectUploader.Target.TargetObjectStorage": "{\"aws-s3-storage\": {\"bucket\": \"flight-gateway-test\",\"subfolder\": \"\",\"access-key\": \"AKIAJ6EPASSWORDV6TLPYV\",\"secret-key\":\"eklmmlevkqfvcuPASSWORDtpmam\",\"id\": 28716,\"name\": \"S3 AWS East\"}",
                "ObjectUploader.Schedule._sp_frequency": "once"
            }
        }
    }
}

]

现在我要做的是将JSON的这一特定部分转换为带有转义字符的字符串,如下所示:

"ObjectUploader.Target.TargetObjectStorage": "{\"aws-s3-storage\": {\"bucket\": \"flight-gateway-test\",\"subfolder\": \"\",\"access-key\": \"AKIAJ6EPASSWORDV6TLPYV\",\"secret-key\":\"eklmmlevkqfvcuPASSWORDtpmam\",\"id\": 28716,\"name\": \"S3 AWS East\"}"

之所以需要将其设置为字符串格式,是因为我的目标是接受这种方式。当我做JsonConvert.SerializeObject(jobList,Formatting.Indented);这就是我得到的:

[{
"job": {
  "jobName": "Flight_Test",
  "fields": {
    "jobGroupName": "ObjectUploader",
    "jobTemplateLibraryName": "Object_Mover_Workflows",
    "jobTemplateName": "ObjectUploader",
    "jobArgs": {
      "ObjectUploader.Source.SourceAgent": "sig_windows",
      "ObjectUploader.Source.Data": "<siglist type=\"filedir\"><el v=\"\\\\is-us-se01.com\\repo\\test\\test\" t=\"d\"></el></siglist>",
      "ObjectUploader.Target.TargetAgent": "sig-dev.com",
      "ObjectUploader.Target.TargetObjectStorage": {
        "aws-s3-storage-access": {
          "BucketName": "flight-test",
          "SubFolder": "TestFolder",
          "AccessKey": "PASSWORD",
          "SecretKey": "PASSWORD",
          "ProfileName": null,
          "BucketId": 28716
        }
      },
      "ObjectUploader.Schedule._sp_frequency": "none"
    }
  }
}

} ]

如您所见,ObjectUploader.Target.TargetObjectStorage已以正确的JSON格式序列化,但是API无法以这种方式解析它,API接受的唯一格式是带有换行符等的JSON。 >

"ObjectUploader.Target.TargetObjectStorage": "{\"aws-s3-storage\": {\"bucket\": \"flight-gateway-test\",\"subfolder\": \"\",\"access-key\": \"AKIAJ6EPASSWORDV6TLPYV\",\"secret-key\":\"eklmmlevkqfvcuPASSWORDtpmam\",\"id\": 28716,\"name\": \"S3 AWS East\"}"

我获得当前所需格式的方法是通过一个在线网站,但我想知道C#是否具有某些功能,可以为我提供所需的结果。

1 个答案:

答案 0 :(得分:0)

您可以创建一个转换器来执行此操作:

state.x77 %>% state.name %>% which.max(.,"Illiteracy")


state.x77 %>% select(.,max(state.name))  


state.x77 %>%
group_by(state.name) %>%
summarize(max(.,))

用法示例:

private class StringObjectPropertyConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(T) == objectType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType != JsonToken.String)
        {
            throw new Exception("Expected string");
        }
        var serialized = reader.Value.ToString();
        using (TextReader tr = new StringReader(serialized))
        {
            if (existingValue == null)
            {
                existingValue = serializer.Deserialize(tr, objectType);
            }
            else
            {
                serializer.Populate(tr, existingValue);
            }
        }
        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        StringBuilder sb = new StringBuilder();
        using (TextWriter tw = new StringWriter(sb))
        {
            serializer.Serialize(tw, value);
        }
        serializer.Serialize(writer, sb.ToString());
    }
}

产生JSON:

public class Person
{
    public string Name { get; set; }
    public string Gender { get; set; }
}

public class Test
{
    [JsonConverter(typeof(StringObjectPropertyConverter<Person>))]
    public Person Person { get; set; }
}

var testObj = new Test()
{
    Person = new Person() { Name = "John", Gender = "Male" }
};
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(testObj);

同样,它也可以将其反序列化为对象结构。