最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there an ASP.NET Boilerplate Way of getting JSON data? - Stack Overflow

programmeradmin1浏览0评论

I am currently trying this, but I keep seeing the dreaded error:

Unexpected token o in JSON at position 1

I am struggling to find a solution and was wondering if anyone has any tips on how to solve this?

The class being serialized to JSON:

[Serializable]
public class GeoCoordinate
{
    public GeoCoordinate()
    {
    }

    [JsonProperty(PropertyName = "lat")]
    public double Latitude { get; }

    [JsonProperty(PropertyName = "long")]
    public double Longitude { get; }

    public GeoCoordinate(double latitude, double longitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", Latitude, Longitude);
    }
}

Ajax call:

function getLocationData() {
    jQuery.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: "GET",
        dataType: "json",
        async: true,
        success: function (data) {
            var myArray = jQuery.parseJSON(data);
            locations = [];
            $.each(myArray, function (index, element) {
                locations.push([element.lat, element.long]);
            });
        }
    });
}

Controller:

[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

AppService:

public async Task<IList<GeoCoordinate>> GetAllGeoCoordinates()
{
    var geoCoordinates = await Repository.GetAll()
        .Where(x => !x.Disabled && !x.Latitude.Equals(0) && !x.Longitude.Equals(0))
        .Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
        .ToListAsync();

    return geoCoordinates;
}

Console.log of data before attempted call to parseJSON:

console.log(data);
var myArray = jQuery.parseJSON(data);

I am currently trying this, but I keep seeing the dreaded error:

Unexpected token o in JSON at position 1

I am struggling to find a solution and was wondering if anyone has any tips on how to solve this?

The class being serialized to JSON:

[Serializable]
public class GeoCoordinate
{
    public GeoCoordinate()
    {
    }

    [JsonProperty(PropertyName = "lat")]
    public double Latitude { get; }

    [JsonProperty(PropertyName = "long")]
    public double Longitude { get; }

    public GeoCoordinate(double latitude, double longitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", Latitude, Longitude);
    }
}

Ajax call:

function getLocationData() {
    jQuery.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: "GET",
        dataType: "json",
        async: true,
        success: function (data) {
            var myArray = jQuery.parseJSON(data);
            locations = [];
            $.each(myArray, function (index, element) {
                locations.push([element.lat, element.long]);
            });
        }
    });
}

Controller:

[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

AppService:

public async Task<IList<GeoCoordinate>> GetAllGeoCoordinates()
{
    var geoCoordinates = await Repository.GetAll()
        .Where(x => !x.Disabled && !x.Latitude.Equals(0) && !x.Longitude.Equals(0))
        .Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
        .ToListAsync();

    return geoCoordinates;
}

Console.log of data before attempted call to parseJSON:

console.log(data);
var myArray = jQuery.parseJSON(data);

Share Improve this question edited Mar 23, 2018 at 2:37 aaron 43.2k6 gold badges53 silver badges111 bronze badges asked Mar 22, 2018 at 8:26 jazbjazb 5,8296 gold badges40 silver badges44 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

Coincidentally, there is a section called The ASP.NET Boilerplate Way that exactly addresses this.

Note that only point 2 is specific to ABP:

  1. GetLocationsAsync returns a JSON object and not a string, so you should not call parseJSON.

    You can reproduce the error message with: jQuery.parseJSON({});

  2. ABP wraps JsonResult. From the documentation on AJAX Return Messages:

    This return format is recognized and handled by the abp.ajax function.

    You could use [DontWrapResult] attribute, but you might as well leverage on ABP here. abp.ajax handles the display of error messages if you throw a UserFriendlyException.

  3. Since ajax is asynchronous, getLocationData cannot return locations directly.

    You can return a chained Promise. If you're new to Promises, read Using Promises first.

  4. There's a neater way than $.each and push.

    You can use map.

Finally:

function getLocationData() {
    return abp.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: 'GET'
    }).then(function (result) {
        return result.map(function (element) {
            return [element.lat, element.long];
        });
    });
}

Usage:

getLocationData().then(function (locations) {
    console.log(locations);
});

ASP.NET Boilerplate wraps ASP.NET MVC action results by default if the return type is a JsonResult. So if you want to get the result you can disable wrapping. Try adding [DontWrapResult] attribute to the GetLocationsAsync method.

[DontWrapResult]
[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

PS: You don't need to add this attribute. You can get it from result field. Inspect the response via your browser's dev console to see how it's wrapped.

发布评论

评论列表(0)

  1. 暂无评论