【问题标题】:Json From .Net Server to android clientJson 从 .Net 服务器到 android 客户端
【发布时间】:2016-07-19 00:38:11
【问题描述】:

我正在尝试从 android 应用程序调用 ApiController。 这是 api 控制器:

[AcceptVerbs("GET", "POST")]        
public string Get(string coords)      
{
  using (var context = new Entities())
  {
          var records = from poi in context.Pois
                     where poi.Latitude >= fromLatitude &&
                           poi.Latitude <= toLatitude &&
                           poi.Longitude >= fromLongitude &&
                           poi.Longitude <= toLongitude
                     select new
                     {
                         poiName = poi.Name,
                         poiLatitude = poi.Latitude,
                         poiLongitude = poi.Longitude
                     };

          return JsonConvert(records);
      }
  }
}

private string JsonConvert(object records)
{
    return Newtonsoft.Json.JsonConvert.SerializeObject(records,);
}

在 android 代码中,我正在使用新的 JSON(字符串)创建 json 数组。 问题是 java 抛出异常:json 字符串无效。 当我查看调试器时,我看到字符串在 ", 而java不知道如何解析它。

问题出在哪里? 谢谢

更新:已解决。 WebApi 以 json 作为字符串返回 XML。将 WebApi 更改为不返回 XML,然后将其更改为返回对象(并删除了 JSONConvert) - 它可以工作。

【问题讨论】:

  • 发布一些 JSON 示例可能会有所帮助。
  • 这是 JSON 的值:"[{\\"poiID\\":1,\\"poiLatitude\\":32.00127,\\"poiLongitude\\":34.8212547\\ "}]"
  • 为了解析我创建 JSONArray - org.JSON.JSONArray

标签: java android json


【解决方案1】:

我知道这是一个老问题,但我遇到了类似的问题并找到了解决方案。

在我的情况下,我必须将一个复杂的 JSON 对象(嵌套)从 .NET 客户端传递到 Java Rest API,并且使用了一个字符串参数,由于双反斜杠(我对其进行了序列化),该字符串参数被证明是无效的 JSON所以它被转义了,然后.NET在发送之前再次转义它)。

所以,为了避免我使用了 StringContent

MyType obj = new MyType()
{
...
};

string obJSON = JsonConvert.SerializeObject(obj);
StringContent sc = new StringContent(obJSON, Encoding.UTF8,"application/json");
HttpResponseMessage response = client.PostAsync(ruta, sc).Result;

希望这对某人有所帮助!

【讨论】:

    猜你喜欢
    • 2016-03-16
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多