Couchbaselite-Exception: Bad or missing JSON - android

I try to save properties in a Couchbase-document in Android.
The properties hold a JSONArray with several JSONObjects.
When I do document.putproperties(myproperties) a couchbaseliteexception with state 400 and the message "bad or missing json" is thrown".
So the JSONArray looks like:
"some_prop" -> "[
{
"content":"someContent",
"key2":"",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
},
{
"content":"Some other content",
"key2":"something",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
}]"
Can anyone tell me whats the problem with this JSON?
EDIT:
the JSONArray with the corresponding key is saved in a hashmap like it is explained in:
http://developer.couchbase.com/mobile/develop/guides/couchbase-lite/native-api/document/index.html
EDIT 2:
The Method where the update is executed and the JSONArray is filled:
private void updateDoc(ArrayList<MyObject> objects) {
Document document = getDocument();
// Update the document with more data
Map<String, Object> updatedProperties = new HashMap<>();
JSONArray objectArray = new JSONArray();
//fill array with data
for(MyObject element : objects) {
JSONObject jsonObjects = element.toJSONObject();
if(jsonObjects != null) {
objectArray.put(jsonObjects);
}
}
//set data to property map
updatedProperties.put(MYOBJECT_PROP_IDENTIFIER, objectArray);
try {
// Save properties to the Couchbase local Couchbase Lite DB
document.putProperties(updatedProperties);
} catch (CouchbaseLiteException e) {
}
}

Not sure if this is what you're looking for,
You can also use something like http://jsonlint.com to verify your son
{
"some_prop": [
{
"content": "someContent",
"key2": "",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
},
{
"content": "Some other content",
"key2": "something",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
}
]
}

Finally I found a solution to the problem:
I don't use JSONObject or JSONArray anymore but save my data in ArrayList and put each element directly into the database. so i don't have an Array with all the elements which but a lot of single elements direktly in the document. To accesss them later I save also the number of elements in the DB. Each element has the index as a prefix so it can be identified later on.
That's not quite a nice way but it works..

Related

Json Parsing in android issue

I am developiing a android application for the blind and i used the Karios api and everything has worked out great
And i get the output of the api as
{
"images": [
{
"time": 0.86679,
"status": "Complete",
"file": "face_57078c26c5baf.jpg",
"width": 776,
"height": 570,
"faces": [
{
"topLeftX": 94,
"topLeftY": 95,
"width": 189,
"height": 189,
"leftEyeCenterX": 152.275,
"leftEyeCenterY": 172.175,
"rightEyeCenterX": 225.5125,
"rightEyeCenterY": 168.2375,
"noseTipX": 188.83536147895,
"noseTipY": 209.93069059821,
"noseBtwEyesX": 188.69509888285,
"noseBtwEyesY": 163.76829692552,
"chinTipX": 194.90835566598,
"chinTipY": 272.94500076858,
"leftEyeCornerLeftX": 139.748828125,
"leftEyeCornerLeftY": 173.99609375,
"leftEyeCornerRightX": 167.2744140625,
"leftEyeCornerRightY": 173.6638671875,
"rightEyeCornerLeftX": 210.7591796875,
"rightEyeCornerLeftY": 171.3259765625,
"rightEyeCornerRightX": 236.955859375,
"rightEyeCornerRightY": 167.622265625,
"rightEarTragusX": -1,
"rightEarTragusY": -1,
"leftEarTragusX": -1,
"leftEarTragusY": -1,
"leftEyeBrowLeftX": 124.96433022747,
"leftEyeBrowLeftY": 160.66254675843,
"leftEyeBrowMiddleX": 144.98960402463,
"leftEyeBrowMiddleY": 151.01911416052,
"leftEyeBrowRightX": 171.91583787312,
"leftEyeBrowRightY": 155.84335467715,
"rightEyeBrowLeftX": 204.04144319738,
"rightEyeBrowLeftY": 153.33575045711,
"rightEyeBrowMiddleX": 228.74564647717,
"rightEyeBrowMiddleY": 144.48143172972,
"rightEyeBrowRightX": 247.64047899459,
"rightEyeBrowRightY": 149.93257330135,
"nostrilLeftHoleBottomX": 179.40484698779,
"nostrilLeftHoleBottomY": 222.21013668835,
"nostrilRightHoleBottomX": 200.05702183911,
"nostrilRightHoleBottomY": 220.59810540404,
"nostrilLeftSideX": 168.63097309489,
"nostrilLeftSideY": 217.27943710651,
"nostrilRightSideX": 211.08266584481,
"nostrilRightSideY": 213.96581724432,
"lipCornerLeftX": 164.95407560776,
"lipCornerLeftY": 244.11611360475,
"lipLineMiddleX": 192.40075144939,
"lipLineMiddleY": 240.81939551421,
"lipCornerRightX": 219.84742729102,
"lipCornerRightY": 237.52267742366,
"pitch": -1.1481443688526,
"yaw": 0.95481944449499,
"roll": -3.7557902314114,
"attributes": {
"gender": {
"time": 0.06871,
"type": "F",
"confidence": "90%"
}
}
}
]
}
]
}
How can I get to the type value of a face in android? Thanks in advance.
It should be something like this...
private String returnPersonType(String output) {
String type = "";
try {
JSONObject jsonObject = new JSONObject(output);
if (jsonObject.has("images")) {
JSONArray imagesArray = jsonObject.getJSONArray("images");
if (imagesArray.length() > 0 && imagesArray.getJSONObject(0).has("faces")) {
JSONArray facesArray = imagesArray.getJSONObject(0).getJSONArray("faces");
if (facesArray.length() > 0 && facesArray.getJSONObject(0).has("attributes") && facesArray.getJSONObject(0).getJSONObject("attributes").has("gender")) {
type = facesArray.getJSONObject(0).getJSONObject("attributes").getJSONObject("gender").getString("type");
}
}
}
} catch (JSONException e) {
}
return type;
}
In above response
faces is a JSONArray with one value
Get JSONArray of faces
Then Get JSONObject from faces JSONArray of 0 index and get values that you need.
First thing to keep in mind while parsing
{- JSONObject function needs to be called
[- JSONArray function needs to be called
here is the solution to your problem if you only want to reach faces[0] object..
{
....
....
JSONObject jsonRootObject=new JSONObject("/*Your son data as string or any string variable containing your son data*/");
JSONArray jsonArray=jsonRootObject.optJSONArray("images");
JSONObject object0=jsonArray.optJSONObject(0);
JSONArray faces=object0.optJSONArray("faces");
JSONObject face0=faces.optJSONObject(0);
//Now you can call any object data by using its key. following code gets height stored int it
String t=face0.optString("height");
...
...
}
... represents your code which you will write as per your need.
Good luck with your programming.
There is one simple Solution to get it easily.
Convert your Json with This link will convert your json to POJO class
you will get some classes as result.
And by following demo code in your onPostExecute() method , you can get Faces Data,
String json = new Gson().toJson(object);
YourMainPOJO newProjectList = new Gson().fromJson(json,
YourMainPOJO.class);
ArrayList<YourImagePOJO> cpImageData = cp.getImages();
ArrayList<YourFacePOJO> cpFaceData = cpImageData. getFaces();
String topLeftY = cpFaceData.getTopLeftY ();
String topLeftX = cpFaceData.getTopLeftX ();
This is the simple way you can get your result easily, without any hassle.
res.images[0].faces[0].attributes.gender.type
Assuming your response is in res

Android Json parsing with sqlite

I am new in android JSON parsing android.
Below I mentioned my JSON value, please give the solution to how to parse the JSON value, thanks in advance my JSON Data:
Here I have category, categorybook, subcategory inside have subbook. I want to parse all the value and store it into sqlite with separate.
Like category book and sucategory book are stored seperate column in android sqlite table:
[
"category": {
"id": "1",
"name": "Education",
"categorybooks": [],
"subcategory": [
{
"id": "1",
"name": "tamil",
"subcategorybooks": []
},
{
"id": "2",
"name": "english",
"subcategorybooks": []
},
{
"id": "5",
"name": "maths",
"subcategorybooks": []
},
{
"id": "6",
"name": "science,
"subcategorybooks": []
},
{
"id": "7",
"name": "social",
"subcategorybooks": []
}
}
]
Here i have category 2 and its sub category books:
[
"category": {
"id": "2",
"name": "sports",
"categorybooks": [
{
"id": "4",
"name": "football",
},
{
"id": "5",
"name": "cricket",
}
],
"subcategory": []
}
]
First of all, you will need the VolleyLibrary. Then, you will need the GSON library. When creating GSON Request, you put the Object you want to get deserialized automatically from JSON, so you wont have to parse it manualy.
Second thing, you would want to create a db class that extends SQLiteHelper. When you create database, add the methods for adding, update and removing a row for every table that you create.
Below are the links that you need.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://medium.com/android-news/android-networking-i-okhttp-volley-and-gson-72004efff196#.wp5lstsfv
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I will assume you already have the content of your json, if not you can use any Http Connection to get the content.
You can use Gson to parse your json content, first of all, you need to create your models based on your Json:
//note: Gson identify the attributes name as the same of from your
//json, if not you have to put an annotation above each attribute of
//your class:
public class Category(){
int id;
String name;
List<CategoryBook> categoryBooks;
}
public class CategoryBook(){
int id;
String name;
}
public class SubCategory(){
//Based on your json I will assume the attribute of this class
// is a model that have a list of an object that have an id and a name
//and a list of subcategorybooks
}
public class SubCategoryBooks(){
//class attributes that you not mentioned in your json
}
Then you just need to parse your object from content using gson,
if you have some doubts about how to parse using Gson follow this tutorial
For insert into database separate, you already have your objects with getters and setters, for example
you can get the List<CategoryBook> from your CategoryModel, then your can insert this list
inside a separate table of your database.
Hope It's Help you
JSONObject jsonObject = new JSONObject();
jsonObject.put("category",loaddata());
public JSONObject loaddata(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","1");
jsonObject.put("name","Education");
jsonObject.put("categorybooks",addcategorybooks());
jsonObject.put("subcategory","addsubcategory()");
return jsonObject;
}
public JSONArray addcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategory(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
jObj.put("subcategorybooks", addsubcategorybooks());
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
If i understood you correctly, the main problem is to get java model object from json.
There are several ways to do it. The most common are:
Using built-in tools to operate with Json. In this case you get org.json.JSONObject and get values using it's methods. See details f.e. here
Using gson library. In this case you create model class and you can fill the object with one code line. smth like Category category = gson.fromJson(yourJsonString, Category.class); See details in official tutorial

Get json array length and looping

So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code

Parsing multiple json arrays in a json object

I have a json object being returned that has multiple arrays within the json object. I am able to parse a json object if it has one array in it (with jObject.getJSONArray("2013-10-30")), but not multiple. The amount of arrays (i.e. the dates) would be changing almost everyday (some days there wouldn't be any) and that is where I get stuck. I'm not sure how to get a list of all the array names and then iterator through that.
{
"2013-10-30": [
{
"id": "399",
"Time": "00:50:46"
}
],
"2013-10-29": [
{
"id": "398",
"Time": "21:44:09"
},
{
"id": "393",
"Time": "10:53:01"
}
]
}
You should iterate over the keys and get the JSONArray for each key as follow:
Iterator<String> keys = jObject.keys();
while(keys.hasNext()){
String key = keys.next();
try{
JSONArray array = jObject.getJSONArray(key);
// do something with the array
// ...
}
catch(Exception e){
e.printStackTrace()
}
}

Parsing json string with multiple objects

How can I parse the following to retrieve the following.
{"docs": [
"SolrDocument[{content_type=[text/plain], description=/mnt/sdcard/A.txt, id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114, name=uploadedfile}]",
"SolrDocument[{content_type=[text/plain], description=asdf.png, id=9fb20d5d-cf39-4635-9a22-64560124809e, name=uploadedfile}]"]
}
I need to retrieve description into a string array and id to another string array.
I tried
a="docs"
JSONObject jobj = new JSONObject(line);
JSONArray IDS = (JSONArray) jobj.get(a);
This works but it returns an array of strings
The data you are trying to parse isn't valid JSON, so you are now in RegEx territory. So reading each line out of the JSONArray you could extract what you are after like this:
String data = "SolrDocument[{content_type=[text/plain], description=/mnt/sdcard/A.txt, id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114, name=uploadedfile}]";
Pattern values = Pattern.compile("(description|id)=([\\S]+),", Pattern.CASE_INSENSITIVE);
Matcher matches = values.matcher(data);
while(matches.find()) {
System.out.println(matches.group(1) + "=" + matches.group(2));
}
This will print out:
description=/mnt/sdcard/A.txt
id=4df6fa43-1a99-4475-bc5b-80dd0ab6d114
The elements inside the JSONArray "docs" are not valid JSON objects. You must have "key":"value" pairs in order to be valid.
For example:
{
"docs": [
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
},
{
"id": 912345678902,
"text": "#android_newb just use android.util.JsonReader!",
"geo": [
50.454722,
-104.606667
],
"user": {
"name": "jesse",
"followers_count": 2
}
}
]
}
There are plenty of sites that can validate your JSON, for example JSONLint
Before we can answer your question, fix your JSON.

Categories

Resources