为JProperty.Value(Set)定义字符串转换设置

时间:2017-07-30 12:01:14

标签: vb.net json.net

我有这个扩展功能:

<Extension> Sub SetPropertiesValue(jsontoken As JToken, 
                                   propertypath As String, 
                                   newvalue As Object)
    Dim jsonproperties = jsontoken.SelectTokens(propertypath).OfType(Of JValue).Select(Function(jv) jv.Parent).OfType(Of JProperty)
    For Each jp In jsonproperties
        jp.Value = newvalue
    Next
End Sub

当我以newvalue传递一个非ASCII字符的字符串时,例如“açúcar”,它将属性设置为"propertyname" : "açúcar"

如何告诉JSON.NET转义非ASCII字符,以便操作的重新定位为"propertyname" : "a\u00e7\u00facar"

1 个答案:

答案 0 :(得分:1)

使用Json.NET,在创建JToken层次结构时不会发生字符串转义。它仅在通过设置JsonWriter.StringEscapeHandling最终转换为 JSON字符串时发生。这是因为字符串转义是JSON的字符串表示的工件。由于JToken层次结构表示已经标记化并解析了 JSON,因此不再需要转义字符串文字中的控制字符。

获得JToken根对象后,您可以通过设置JsonSerializerSettings.StringEscapeHandling然后序列化对象来控制最终输出期间的字符串转义:

    Dim settings = New JsonSerializerSettings With { _
        .StringEscapeHandling = StringEscapeHandling.EscapeNonAscii _
    }
    Dim json = JsonConvert.SerializeObject(jsontoken, Formatting.Indented, settings)

或者如果您更喜欢使用较低级别的实用程序,可以使用适当的设置构建自己的JsonTextWriter,如下所示:

    Dim sb = new StringBuilder()
    Using textWriter as new StringWriter(sb)
        Using jsonWriter as new JsonTextWriter(textWriter) With { .StringEscapeHandling = StringEscapeHandling.EscapeNonAscii, .Formatting = Formatting.Indented }
            jsontoken.WriteTo(jsonWriter)
        End Using
    End Using
    Dim json = sb.ToString()

StringEscapeHandling的可能值显示为here

Default         0   Only control characters (e.g. newline) are escaped.
EscapeNonAscii  1   All non-ASCII and control characters (e.g. newline) are escaped.
EscapeHtml      2   HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped. 

示例VB.Net fiddle