简体   繁体   中英

Java - Convert String to String Array

I am new to Java. Please help me. Below is the string after implementing HTTP POST method as a response:

 {"Result":"{  \"Search\": [    {      \"Code\": \"200\"    },    {      \"Message\": \"Fetched successfully\"    },    {      \"Name\": \"1\",      \"id\": \"166\",      \"PID\": \"162\"    }  ]}"}

Now i want to get only Name s in the given String and form a Stirng[] of Name s. Please help me.

You need to first parse this JSON and then iterate through it

http://www.mkyong.com/java/json-simple-example-read-and-write-json/

parsing json with java

https://stackoverflow.com/questions/338586/a-better-java-json-library?rq=1

After you have parsed this JSON text, then its a matter of iterating through the object and keep pushing the values into arraylist

Once you got the arraylist, then you can convert it to a String array

Converting 'ArrayList<String> to 'String[]' in Java

Here use this one:

public class CStringToCharArray {
 public static void main(String[] args) {
    String testString = "This Is Test";
    char[] stringToCharArray = testString.toCharArray();

    for (char output : stringToCharArray) {
        System.out.println(output);
    }
}
}

You can use the below code to extract the names and their values

    List<String> nameValues = new ArrayList<String>();
    Matcher matcher1 = Pattern.compile("\\\\\"Name\\\\\":\\s\\\\\"[^,}\\]]+\\\\\"").matcher(value);
    while (matcher1.find()) {
        String keyValuePair = matcher1.group();
        String[] keyValue = keyValuePair.split(":");
        String val = keyValue[1].trim();
        System.out.println(keyValue[0]);
        System.out.println(">" + val + "<");
        nameValues.add(val.substring(2, val.length() - 2));
    }
    System.out.println(nameValues);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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