【问题标题】:javascript string into object/arrayjavascript字符串到对象/数组
【发布时间】:2021-08-08 15:30:12
【问题描述】:

我正在从 java 代码中接收该字符串: {devices:[3962], contacts:[{_userId='1', _contactId='(+1)1111111', _contactName='Name Surname'}]} 我想将其转换为普通对象,但它不是有效的 JSON 格式。你有什么想法吗?

或者也许有人可以帮助我编写 JAVA 代码。 我想所有的魔法都在这里:

    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 + '\'' +
                    '}';
        }
    }


【问题讨论】:

  • 修复无效 JSON 的来源
  • 我不懂JAVA,所以不会
  • 但是您可以访问 Java 代码?
  • 这不是 JSON,所以如果没有一些繁重的字符串操作,就没有简单的方法来解析它。
  • @alex 请不要在 cmets 中分享问题代码?一行字真的很难全部理解。 (我知道你没有,但这是供将来参考)

标签: javascript java json string format


【解决方案1】:

我更改了您的 java 并改为传递 JSONObject 和 JSONArray。它将为您的 javascript 程序返回一个 json 对象。

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;
    }
}


【讨论】:

    【解决方案2】:

    处理此案例的最佳方法是要求Java 开发人员更改格式以使用有效的 JSON 代码进行响应。然后你可以打电话给JSON.parse,这样就可以了。

    另一种方法是编写某种代码,使其成为有效的 JSON。为此,您需要将每个键包装到 " 引号中,并将 = 替换为 : 符号。

    【讨论】:

      【解决方案3】:

      您可以尝试快速修复字符串。像这样的:

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

      但这是个坏主意。我发布它只是作为临时紧急情况的最后手段。不要在严肃的代码中使用它。

      您需要修复 Java 代码。

      【讨论】:

        【解决方案4】:

        您需要更改以下内容。

        1. ContactItem.toString

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

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

        现在结果应该是{"devices":[3962], "contacts":[{"_userId":"1", "_contactId":"(+1)1111111", "_contactName": "Name Surname"}]}

        现在你可以运行JSON.parse。

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

        【讨论】:

        • 不,这不是它的工作原理。 oracle.com/technical-resources/articles/java/json.html
        • 显然你应该使用更高级的东西,但问题是原始代码已经做了toString的东西,那么修复那个代码有什么问题?
        • 它不可读、容易出错并且是不好的做法。
        • @ChrisG,以及如何以正确的方式做到这一点?也许,你可以分享一些提示?
        • @alex “如何以正确的方式做到这一点?” - 谷歌会告诉你。您不是第一个需要以 JSON 表示的数据的人 -> How much research effort is expected of Stack Overflow users?
        猜你喜欢
        • 2017-08-27
        • 2018-08-31
        • 2013-03-29
        • 2013-04-21
        • 2012-10-11
        • 2022-12-02
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        相关资源
        最近更新 更多