2016-12-27 57 views
0

字符串值我有以下代码(工作)反序列化从Web调用接收到的原始JSON:反序列化的DataContract从内存

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编码)收到的字符串:与(存储在foo

string foo = Convert.FromBase64String("ew0KICAidG9tIjogIjEyMyINCn0="); 

如何解码

ew0KICAidG9tIjogIjEyMyINCn0= 

我通过foo.ReadObject()作为.ReadObject()只接受Stream

回答

1

将其重新写回到流中并将流传递到ReadObject。您可以使用MemoryStream,如here所述。

下面是示例作为匿名类型的方法:

/// <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; 
} 
+0

这很好。稍后再测试一下。如果那里的代码适用于此,将修改您的解决方案并将其标记为已接受。与此同时,我看起来就像是在寻找我喜欢的东西。 :) –

+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); 
} 
+0

'foo'需要被转换到一个'Stream'如'.ReadObject()'只接受型Stream'的'对象。 –

+0

@KraangPrime - 一旦得到foo,请参考* zmbq * answer从foo生成一个流。 – Graffito