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












0















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].










share|improve this question



























    0















    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].










    share|improve this question

























      0












      0








      0








      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].










      share|improve this question














      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].







      ionic3 jax-rs org.json






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 days ago









      aleksejjjaleksejjj

      266




      266
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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");





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54252998%2fionic-httpclient-a-jsonobject-text-must-begin-with-at-1-character-2-line-1%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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");





            share|improve this answer




























              0














              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");





              share|improve this answer


























                0












                0








                0







                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");





                share|improve this answer













                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");






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                aleksejjjaleksejjj

                266




                266






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54252998%2fionic-httpclient-a-jsonobject-text-must-begin-with-at-1-character-2-line-1%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Callistus III

                    Plistias Cous

                    Index Sanctorum