alex
alex

Reputation: 139

javascript string into object/array

I'm receiving that string from java code: {devices:[3962], contacts:[{_userId='1', _contactId='(+1)1111111', _contactName='Name Surname'}]} and I want to convert it into normal object, but it's not a valid JSON format. Do you have any ideas?

Or maybe somebody can help me with JAVA code. I suppose that all the magic goes here:

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
    public String extractDbDump() {
        return "{devices:" + getDevices() + ", contacts:" + getContacts() + "}";
    }
    private String getContacts() {
        List<ContactItem> contactList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + TABLE_CONTACT;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                ContactItem contact = new ContactItem();
                contact.userId = cursor.getString(0);
                contact.contactName = cursor.getString(1);
                contact.contactId = cursor.getString(2);
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        db.close();
        return "" + contactList.toString();
    }
    private String getDevices() {
        List<String> deviceList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + TABLE_DEVICE;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    deviceList.add(cursor.getString(0));
                } while (cursor.moveToNext());
            }
        }
        db.close();
        return deviceList.toString();
    }
    public class ContactItem {
        public String userId;
        public String contactId;
        public String contactName;
        @Override
        public String toString() {
            return "{" +
                    "_userId='" + userId + '\'' +
                    ", _contactId='" + contactId + '\'' +
                    ", _contactName='" + contactName + '\'' +
                    '}';
        }
    }


Upvotes: 0

Views: 109

Answers (4)

ikhvjs
ikhvjs

Reputation: 5977

I change your java and pass JSONObject and JSONArray instead. It will return a json object for your javascript program.

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    public JSONObject extractDbDump() {
        JSONObject json = new JSONObject();
        json.put("devices", getDevices());
        json.put("contacts", getContacts());
        return json;
    }

    private JSONArray getContacts() {
        JSONArray array = new JSONArray();
        String selectQuery = "SELECT * FROM " + TABLE_CONTACT;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                JSONObject item = new JSONObject();
                item.put("_userId", cursor.getString(0));
                item.put("_contactId", cursor.getString(1));
                item.put("_contactName",cursor.getString(2));
                array.put(item);

            } while (cursor.moveToNext());
        }
        db.close();
        return array;
    }

    private JSONArray getDevices() {
        JSONArray array = new JSONArray();
        String selectQuery = "SELECT * FROM " + TABLE_DEVICE;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    array.put(cursor.getString(0));
                } while (cursor.moveToNext());
            }
        }
        db.close();
        return array;
    }
}


Upvotes: 1

Ayzrian
Ayzrian

Reputation: 2465

You need to change the following things.

  1. ContactItem.toString

    public String toString() {
        return "{" +
                "\"_userId\":\"" + userId + '"' +
                ", \"_contactId\":\"" + contactId + '"' +
                ", \"_contactName\":\"" + contactName + '"' +
                '}';
    }
    
  2. extractDbDump

public String extractDbDump() {
    return "{\"devices\":" + getDevices() + ", \"contacts\":" + getContacts() + "}";
}

Now the result should be {"devices":[3962], "contacts":[{"_userId":"1", "_contactId":"(+1)1111111", "_contactName": "Name Surname"}]}

Now you can just run JSON.parse.

const response = `{"devices":[3962], "contacts":[{"_userId":"1", "_contactId":"(+1)1111111", "_contactName": "Name Surname"}]}`;

console.log(JSON.parse(response));

Upvotes: 0

Yuri Khristich
Yuri Khristich

Reputation: 14537

You can try to make a quick fix for the string. Something like this:

var s = `{numbers:[3962], contacts:[{_userId='1', _contactId='(+1)1111111', _contactName='Name Surname'}]}`;

var obj = eval(s.replace(/=/g, ":").replace(/:\[/g, "=[")); // <-- bad practice !!!

console.log(obj);

But it's a bad idea. I post it just as a last resort for temporary emergency cases. Don't use it in a serious code.

You need to fix the Java code instead.

Upvotes: 0

Ayzrian
Ayzrian

Reputation: 2465

The best way to handle the case will be to ask Java developers to change the format to respond with the valid JSON code. Then you could just call JSON.parse and that would work.

Another way will be to write some kind of code that will make it valid JSON. For that you would need to wrap every key into " quotes and replace = with : signs.

Upvotes: 0

Related Questions