从内存中

时间:2016-12-27 20:50:35

标签: c# json string stream datacontractserializer

我有以下代码(可以工作)来反序序化从网络电话中收到的原始json:

public static async Task<Example> GetExample() {
    Example record = new Example();

    using ( WebClient wc = new WebClient() ) {
        wc.Headers.Add( "Accept", "application/json" );

        try {
            DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Example ) );
            using ( Stream s = await wc.OpenReadTaskAsync( "https://example.com/sample.json" ) ) {
                record = ser.ReadObject( s ) as Example;
            }
        } catch ( SerializationException se ) {
            Debug.WriteLine( se.Message );
        } catch ( WebException we ) {
            Debug.WriteLine( we.Message );
        } catch ( Exception e ) {
            Debug.WriteLine( e.Message );
        }
    }
    return record;
}

但是,我有一个不同的场景,我使用的数据是加密的,所以我需要解码base64,然后解密结果以获取json数据。

为了简单起见,假设以下是从服务器收到的字符串(仅限base64编码):

 ew0KICAidG9tIjogIjEyMyINCn0=

使用(存储在foo

进行解码
 string foo = Convert.FromBase64String("ew0KICAidG9tIjogIjEyMyINCn0=");

如何将foo传递给.ReadObject().ReadObject()只接受Stream

2 个答案:

答案 0 :(得分:1)

试试yhis:

using ( Stream s = await wc.OpenReadTaskAsync( "https://example.com/sample.json" ) ) 
{
    string str = Encoding.UTF8.GetString(s.GetBuffer(),0 , s.GetBuffer().Length)
    string foo = Convert.FromBase64String(str);
}

答案 1 :(得分:1)

将其写回流并将流传递给ReadObject。您可以按照here所述使用MemoryStream

以下是匿名类型方法的示例:

/// <summary>
/// Read json from string into class with DataContract properties
/// </summary>
/// <typeparam name="T">DataContract class</typeparam>
/// <param name="json">JSON as a string</param>
/// <param name="encoding">Text encoding format (example Encoding.UTF8)</param>
/// <param name="settings">DataContract settings (can be used to set datetime format, etc)</param>
/// <returns>DataContract class populated with serialized json data</returns>
public static T FromString<T>( string json, Encoding encoding, DataContractJsonSerializerSettings settings ) where T : class {
    T result = null;
    try {
        DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( T ), settings );
        using ( Stream s = new MemoryStream( ( encoding ?? Encoding.UTF8 ).GetBytes( json ?? "" ) ) ) {
            result = ser.ReadObject( s ) as T;
        }
    } catch ( SerializationException se ) {
        Debug.WriteLine( se.Message );
    } catch ( Exception e ) {
        Debug.WriteLine( e.Message );
    }
    return result;
}