2014-02-22 25 views
0

我試圖從Xamarin Android應用程序中的Web請求中解析json。但我得到下面的JSON字符串將Jsonstring從Web請求轉換爲字符串

[{\"type1\":val1,\"type2\":\"val2",\"type3\":\"val3\",\"type4\":val4}, 
{\"type1\":val1,\"type2\":\"val2",\"type3\":\"val3\",\"type4\":val4}] 

如何將其轉換成字符串像下面

[{"type1":"val1","type2":"val2","type3":"val3","type4":"val4"}, 
{"type1":"val1","type2":"val2","type3":"val3","type4":"val4"}] 
+0

過得好的JSON?你確定服務器沒有發送像這樣轉義的字符串嗎? Android或Xamarin沒有內在的東西會導致這種情況。 Xamarin Android中的 – Kiliman

回答

1

你通過複製得到的字符串值C#運行時的價值?如果是這樣,它看起來是正確的一些小錯誤。

[{\"type1\":val1,\"type2\":\"val2",\"type3\":\"val3\",\"type4\":val4}, 
{\"type1\":val1,\"type2\":\"val2",\"type3\":\"val3\",\"type4\":val4}] 

是否應可能爲:

[{\"type1\":\"val1\",\"type2\":\"val2\",\"type3\":\"val3\",\"type4\":\"val4\"}, 
{\"type1\":\"val1\",\"type2\":\"val2\",\"type3\":\"val3\",\"type4\":\"val4\"}] 

一些VAL *的沒有引號在所有和TYPE2失蹤\的報價。

它是您自己的網絡服務?您的網絡請求是否將JSON指定爲格式?如果服務運行JavaScript,它是否調用JSON.stringify(...)來標準化JSON對象?如果您使用的是MVC或其他MS技術,請確保您沒有用雙JSON包裝響應(f.e.通過控制器返回字符串的地方是JSON序列化的字符串,因爲這會導致翻倍)。

驗證Web服務返回的JSON的好工具是PostMan。如果它也返回帶有\的字符串,那麼服務本身就有問題。

這裏是一個小測試儀爲Android與JSON.Net串行:

using System; 
using Android.App; 
using Android.Content; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 
using Android.OS; 
using System.Collections.Generic; 
using Android.Util; 

namespace JsonTest 
{ 
    public class TypeClass 
    { 
     public string type1 { get; set; } 
     public string type2 { get; set; } 
     public string type3 { get; set; } 
     public string type4 { get; set; } 
    } 

    [Activity (Label = "JsonTest", MainLauncher = true)] 
    public class MainActivity : Activity 
    { 
     int count = 1; 

     private const string JsonText = "[{\"type1\":\"val1\",\"type2\":\"val2\",\"type3\":\"val3\",\"type4\":\"val4\"}," + 
             "{\"type1\":\"val1\",\"type2\":\"val2\",\"type3\":\"val3\",\"type4\":\"val4\"}]"; 



     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate (bundle); 

      // Set our view from the "main" layout resource 
      SetContentView (Resource.Layout.Main); 

      // Get our button from the layout resource, 
      // and attach an event to it 
      Button button = FindViewById<Button> (Resource.Id.myButton); 

      button.Click += delegate 
      { 
       var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TypeClass>>(JsonText); 

       foreach (var t in resp) 
       { 
        Log.Info("Type1", t.type1); 
        Log.Info("Type2", t.type2); 
        Log.Info("Type3", t.type3); 
        Log.Info("Type4", t.type4); 
       } 
      }; 
     } 
    } 
} 
+0

是的,我已經實現了相同。謝謝 – Ponmalar

-1

試試這個

String jsonString = json.replaceAll("\\\\", ""); 
+0

,沒有像string.replaceall這樣的方法。此外,我試着用這個「\\\\」替換方法,不工作 – Ponmalar