【问题标题】:Best way to convert string of data to JSON object将数据字符串转换为 JSON 对象的最佳方法
【发布时间】:2021-08-03 20:58:07
【问题描述】:

我有一个包含以下格式信息的字符串:

Maltese Age: 2 Price: $500
https://images.google/image
Staffy Age: 1 Price: $500
https://images.google/image
Yorkie Age: 2 Price: $300
https://images.google/image

我的目标是把上面的变成这样:

Dogs:
{
     "dog": "Pomeranian",
"info": {
    "url": "https://images.google.com/image",
    "age": 2,
    "price": 1000
}


当然,对于我在字符串中的所有宠物,我会在后面和第四个循环。

【问题讨论】:

  • 你已经在使用任何 json 库了吗?
  • 我正在使用 org.json,是的
  • 使用正则表达式获取不同的组,并使用您的json库将结果转换为您描述的JSON对象。

标签: java json string parsing


【解决方案1】:

如果你使用正则表达式,你可以得到这样的值:

JSONArray arr = new JSONArray();
Matcher m = Pattern.compile("([^ \\r\\n]*) Age: ?(\\d+) Price: ?\\$?(\\d+(?:\\.\\d*)?)\\r?\\n(http[^ \\r\\n]*)").matcher(str);
while (m.find()) {
    String dog = m.group(1);
    String age = m.group(2);
    String price = m.group(3);
    String url = m.group(4);

    // Add to a JSON object using your preferred JSON library
    // Example:
    JSONObject obj = new JSONObject();
    obj.put("dog",dog);

    JSONObject info = new JSONObject();
    info.put("age",age);
    info.put("price",price);
    info.put("url",url);

    obj.put("info",info);
    arr.put(obj);
}

【讨论】:

    【解决方案2】:

    可能有多种方法可以做到,但一种方法可能如下。

    您可以先将文本分成几行。

    var lines = text.split("\n");
    

    那你知道奇数行是网址,偶数行是狗信息。

    List<JsonObject> objects = new ArrayList<>();
    for(int i=0; i < lines.length; i++) {
      var line = lines[i];
      if(i % 2 == 0) {
         // apply regex solution given in the other answer
         // to extract the dog information
      } else {
        url = line;
        // since json objects are complete on odd lines
        // build json and add it to the list
        var jsonObject = ...;
        objects.add(jsonObject);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 2021-08-24
      • 2014-06-21
      • 1970-01-01
      • 2011-03-29
      • 2017-01-08
      相关资源
      最近更新 更多