Search code examples
ionic3jax-rsorg.json

Ionic HttpClient: A JSONObject text must begin with '{' at 1 [character 2 line 1]


I have a Java REST API that uses org.json in which I have a method putJson() that parses incoming JSON data and saves it to a database table.

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.json.JSONArray;
import org.json.JSONObject;

@Path("consumptions")
public class ConsumptionsResource extends Database {

    @Context
    private UriInfo context;

    public ConsumptionsResource() {
        this.openConnection();
    }

    @PUT
    @Path("{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    public boolean putJson(@PathParam("id") String id, String content) {
        boolean ok = true;
        JSONObject json = new JSONObject(content);
        String date = json.getString("pvm");
        String time = json.getString("klo");
        String consumption = json.getString("kulutus");

        try {
            String sql = "UPDATE kulutus SET pvm = ?, klo = ?, kulutus = ? WHERE id = ?";
            this.preparedstatement = yhteys.prepareStatement(sql);
            this.preparedstatement.setString(1, pvm);
            this.preparedstatement.setString(2, klo);
            this.preparedstatement.setString(3, kulutus);
            this.preparedstatement.setString(4, String.valueOf(id));
            this.preparedstatement.execute();
            this.closeConnection();
        } catch (Exception e) {
            e.printStackTrace();
            ok = false;
        }
        return ok;
    }
}

I also have an Ionic 3 application that connects to this API with PUT method and JSON data. counter.ts:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { KulutusProvider } from '../../providers/consumption/consumption';
import { consumption } from '../../app/consumption.interface';

@IonicPage()
@Component({
  selector: 'page-counter',
  templateUrl: 'counter.html',
})
export class CounterPage {

  date: string = new Date().toLocaleDateString();
  last_smoked: string;
  counter: number = 0;
  data = {} as consumption;

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public kulutusProvider: KulutusProvider
    ) {
  }

  ionViewDidLoad() {
    let current_day = this.yyyy_mm_dd();
    this.consumptionProvider.getConsumption(current_day).then((data) => {
      this.data = data[0];
    }, (error) => {
      this.data = error;
    });
  }

  addOne = () :void => {
    this.data.consumption += 1;
    this.consumptionProvider.setConsumption(this.data).then((value) => {
      console.log(value);
    });
  }

  yyyy_mm_dd = () :string => {
    let year = new Date().getFullYear();
    let month = `0${new Date().getMonth()+1}`;
    let day = new Date().getDate();
    return `${year}-${month}-${day}`;
  }

}

Here is the provider consumption.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { pack } from '../../app/aski.interface';
import { consumption } from '../../app/kulutus.interface';

@Injectable()
export class ConsumptionProvider {

  constructor(public http: HttpClient, public storage: Storage) { }

  setPack(pack: pack) {
    this.storage.set("pack_info", pack);
  }

  getConsumption(date: string) {
    return new Promise((resolve, reject) => {
      this.http.get(`http://localhost:8080/savukelaskuri/webresources/consumptions/${pvm}`)
        .subscribe((data) => {
          resolve(data);
        }, (error) => {
          reject(error);
        })
    })
  }

  setConsumption(data: consumption) {
    return new Promise((resolve, reject) => {
      this.http.put(`http://localhost:8080/savukelaskuri/webresources/kulutukset/${data.date}`, data[0])
        .subscribe((data) => {
          resolve(data);
        }, (error) => {
          reject(error);
        });
    })
  }

}

I was expecting to be able to parse the JSON data and then save it to database, but instead I am getting this error org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1].


Solution

  • setConsumption() needs to have just data as the PUT body instead of data[0].

    setConsumption(data: consumption) {
        return new Promise((resolve, reject) => {
          this.http.put(`http://localhost:8080/savukelaskuri/webresources/kulutukset/${data.date}`, data)
            .subscribe((data) => {
              resolve(data);
            }, (error) => {
              reject(error);
            });
        })
      }
    

    On ConsummptionResource class putJson() instead of having type string

    String consumption = json.getString("kulutus");
    

    consumption needs to be an integer

    int consumption = json.getint("kulutus");