Xamarin.Forms中带有GetAsync(url)和JsonConvert的问题

时间:2019-04-26 10:48:34

标签: c# json api xamarin.forms json.net

这种情况应该很简单,但是我有一个我不知道如何解决的小错误。我正在使用Xamarin.Forms应用程序,该应用程序对PC中运行的localhost API进行了一些API调用。这是API调用的主要部分:

try
{
    HttpClient client = new HttpClient();
    client.MaxResponseContentBufferSize = BUFFER_SIZE;
    client.DefaultRequestHeaders.Add(CULTURE_ID, "es");
    client.DefaultRequestHeaders.Add(VALUE, LAST_WEEK_VALUE);
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BEARER, token);

    var content = new StringContent("", System.Text.Encoding.UTF8, APPLICATION_JSON);

    HttpResponseMessage response = await client.GetAsync(url);
    var result = await response.Content.ReadAsStringAsync();
    List<SubProductParser> prices;
    try
    {
        prices = JsonConvert.DeserializeObject<List<SubProductParser>>(result);
    }
    catch
    {
        // exception missin the final character in JSON "]"
    }

    return prices.ElementAt(0);
}
catch
{
    return null;
}

尝试进行反序列化之前,result变量的内容: Variable result content

您看到的不是有效的JSON格式,这很奇怪,因为如您在下一个屏幕截图中看到的那样,当我使用POSTMAN进行相同的API调用时,它总是可以完美地工作,但是我不知道为什么有时不当我在应用程序中进行通话时,将接收所有JSON内容。

API call with POSTMAN

任何想法,在调试中看到变量result的内容,有时没有JSON“]”的最后一个字符,API调用是在以这种方式点击按钮后进行的:

private async void Handle_Item_Tapped(object sender, ItemTappedEventArgs e)
{
    var selected = e.Item as ProductParser;
    var lastPrice= await ApiConnector.GetLastWeekSubProductPrices(
        App.ViewModel.LoginViewModel.SesionToken,
        subCatViewModel.Selected.ProductId,
        subCatViewModel.Selected.Id);
    await subCatViewModel.IsFavorite();
    subCatViewModel.BarViewModel.Selected = selected;
    subCatViewModel.BarViewModel.Categories = _categories;
    subCatViewModel.LinearViewModel.Selected = selected;
    subCatViewModel.LinearViewModel.Categories = _categories;
    await Navigation.PushAsync(new Graphs(subCatViewModel));
}

实现此API调用的API函数,该API是使用php在Larvael中开发的。我试图尽可能简化它们:

public static function getLastWeekPrices($cultureId)
{
  self::initialize();
  $year = self::getLastYear();
  $prejson = json_encode(DB::table('product')
  ->join(SOME_CONDITIONS..)
  ...
  ->where(SOME_CONDITIONS..)
  ...
  ->select(SOME_ROWS)
  ->get());

  $currentWeek = self::getCurrentWeek();
  $json_decoded = json_decode($prejson, true);
  $json_final = array();
  foreach ($json_decoded as $slider_value)
  {

      $max_week= DB::table(SOME_CONDITIONS)
      ->max(SOME_CONDITIONS);

      $last_week_price = json_encode(SOME_CONDITIONS)
      ...
      ->get());

      ...
      //ADDING SOME VALUES TO $slider_value
      ...
      array_push($json_final, $slider_value);
  }
  return json_encode($json_final);
}

public static function subProductsPricesQuery($id, $subId, $cultureId, $values)
{
  self::initialize();

  if (self::doesCultureExist($cultureId)){
    if ($values == self::LAST_WEEK) {
      $json = self::getLastWeekSubProductPrices($id, $subId, $cultureId);
    }
    ....
  }
}

public function FunctionCalledInAPIRoute(Request $request, $id, $subId)
{
  try{
      $user = JWTAuth::parseToken()->toUser();
      $json = DatabaseQuerys::subProductsPricesQuery($id, $subId, $request->header("cultureId"),   $request->header("value"));
      return self::jsonIsEmpty($json);
  }catch(JWTException $e){
      return $this->respondInternalError("Any token found!");
  }
}

public static function jsonIsEmpty($products)
{
  self::initialize();
  $initial = $products[0] === "[" ? TRUE : FALSE;
  $final = $products[1] === "]" ? TRUE : FALSE ;


  if (strlen($products) === 0 || ($initial == TRUE && $final == TRUE))
  {
    header('Content-type:application/json;charset=utf-8');
    return (new self)->respondNotFound("Any result found in this category");
  } else {
    header('Content-type:application/json;charset=utf-8');
    return $products;
  }
}

JsonIsEmpty是我创建的一个小方法,用于控制数据库是否返回某些内容,如果函数未返回则返回json_encoder($ array),则始终为[]。 收到错误的JSON时,变量结果的内容:

  [
    {
        "id": 19,
        "name": "Conejo de más de 2125 gr",
        "units": "€/Kg",
        "price": "1.91",
        "week": 10,
        "year": 2019,
        "last_price": "1.79",
        "difference": "0.12",
        "arrow": "up_arrow.png"
    }

如您所见,缺少结尾的“]”。 我实施了一个小测试,以查看应用程序是否正常运行,测试功能以及调用该功能的功能:

     public static function jsonIsEmptyTest($products)
      {
        self::initialize();
        $initial = $products[0] === "[" ? TRUE : FALSE;
        $final = $products[1] === "]" ? TRUE : FALSE ;


        if (strlen($products) === 0 || ($initial == FALSE && $final == FALSE))
        {
          return 1;
        } else {
          return 0;
        }
      }

    public static function the foo(....)
    {
          $correct = 0;
          $wrong = 0;
          for($x = 0; $x < 1000; $x++)
          {
            $json = DatabaseQuerys::subProductsPricesQuery($id, $subId, $request->header("cultureId"),   $request->header("value"));
            print_r($json);
            print_r("\n\n");
            $result = JsonController::jsonIsEmptyTest($json);
            if($result == 0)
            {
              $correct = $correct + 1;
            }
            if($result == 1)
            {
              $wrong = $wrong + 1;
            }

          }
          print_r("Correct: ");
          print_r($correct);
          print_r("\n");
          print_r("Wrong: ");
          print_r($wrong);
          exit();
    }

用邮递员进行API调用的结果是:

Result

0 个答案:

没有答案