2016-12-27 59 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