简体   繁体   中英

Convert Json to string with escape character

I have JSON that i need to convert to string that contains the special characters. Here is the JSON i have:

[{
    "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"
            }
        }
    }
}

]

Now what i want to do is get this specific part of the JSON converted to a string with the escape characters as follows:

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

The reason i need this to be in a string format is because i am targeting accepts it in this manner. When i do JsonConvert.SerializeObject(jobList, Formatting.Indented); this is what i get:

[{
"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"
    }
  }
}

} ]

As you can see the ObjectUploader.Target.TargetObjectStorage gets serialized in the proper JSON format but the API cannot parse it in this manner, the only format the API accepts is the JSON with the newline character etc..:

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

The way i got the current format i need is through a online website but i was wondering if C# has some feature that would give me the result i need.

You could create a converter to do this:

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

Example usage:

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

Produces JSON:

{
    "Person": "{\"Name\":\"John\",\"Gender\":\"Male\"}"
}

Likewise, it can also deserialzie this back to the object structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM