【问题标题】:Xamarin c# for Android : creating a json string?Xamarin c# for Android:创建一个 json 字符串?
【发布时间】:2016-01-15 11:40:42
【问题描述】:

这段代码有问题..

        GlodalVariables.SoftID = "55";

        WebClient client = new WebClient ();
        Uri uri = new Uri ("http://www.example.com/CreateEntry.php");

        string folder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
        Android.Content.Context myContext = Android.App.Application.Context;

        try{

            string  smsUri = System.IO.Path.Combine (folder, "SL.db");
            string myjson = "";
            SQLiteDatabase Mydb = SQLiteDatabase.OpenDatabase(smsUri , null, DatabaseOpenFlags.OpenReadwrite );
            ICursor SMScursor = Mydb.Query ("MySMSLog", null,null, null,null, null ,"TheDate ASC");

            MySMSLog test = new MySMSLog() ;
            if (SMScursor.MoveToFirst ()) {
                while (!SMScursor.IsAfterLast){

                    string number = SMScursor.GetString(SMScursor.GetColumnIndex("TheNumber"));
                    string name = SMScursor.GetString(SMScursor.GetColumnIndex("TheName"));
                    string date = SMScursor.GetString(SMScursor.GetColumnIndex("TheDate"));
                    string direction = SMScursor.GetString(SMScursor.GetColumnIndex("TheDirection"));
                    string text = SMScursor.GetString(SMScursor.GetColumnIndex("TheText"));
                    string id = SMScursor.GetString(SMScursor.GetColumnIndex("Id"));

                    test.Id = int.Parse(id);
                    test.TheDate = date;
                    test.TheDirection = direction ;
                    test.TheName = name;
                    test.TheNumber = number;
                    test.TheText = text;
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject (test);

                    myjson = myjson + output  + " ";

                    SMScursor.MoveToNext ();
                }
            }

            System.Console.WriteLine (myjson    );
            System.Console.WriteLine();
            SMScursor.Close ();

当我将完整的 json 字符串复制到 json 测试站点 (http://jsonlint.com/) 它告诉我刺痛是无效的......

我正在获取所有记录行并将它们放入单个 json 字符串中,然后再将它们推送到服务器..

【问题讨论】:

    标签: c# android json xamarin


    【解决方案1】:

    您不应该以数组形式获得结果吗?所以最终的 json 应该是这样的:

    [{json1},{json2}..] 
    

    如果你只有{json1} {json2},这可能不是一个有效的对象。

    【讨论】:

    • hmmmm ...所以在组合成字符串后,我应该把“[”放在开头,“]”放在最后? ...以及将“”更改为“,”
    • 谢谢!!经过测试并成为一个有效的字符串..就像一个魅力!!
    【解决方案2】:

    另一种解决方案是构建“MySMSLog”对象的集合,然后通过 JSonConvert 序列化集合吗?这样你就不用担心通过你自己的字符串操作来获得正确的结构。

    这很可能还会在未来证明您的代码在 JSON 标准发生变化的荒谬机会上,因为 NewtonSoft 库也将被更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多