简体   繁体   English

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

[英]Best way to convert string of data to JSON object

I have a string containing information in the following format:我有一个包含以下格式信息的字符串:

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

My goal, is to turn the above into something like this:我的目标是将上面的内容变成这样:

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


And of course loop around back and fourth for all of the pets I have in the string.当然,对于我在绳子上的所有宠物,我都会绕回来和第四圈。

If you use regular expressions you can get the values like this:如果您使用正则表达式,您可以获得如下值:

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

There are probably multiple ways to do it, but one way to do it may be something as follows.可能有多种方法可以做到这一点,但一种方法可能如下。

You can start by splitting your text into lines.您可以从将文本分成几行开始。

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

Then you know that odd lines are URLs, and even lines are dog information.然后你知道奇数行是 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM