将数据字符串转换为 JSON 对象的最佳方法

时间:2021-05-13 15:03:11

标签: java json string parsing

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

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
}


当然,我在字符串中的所有宠物都循环往回和第四个循环。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

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

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

那么你知道奇数行是 URL,偶数行是狗信息。

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);
  }
}
相关问题