user2326860
user2326860

Reputation: 137

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 Names in the given String and form a Stirng[] of Names. Please help me.

Upvotes: 1

Views: 7749

Answers (3)

Dev Blanked
Dev Blanked

Reputation: 8865

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

Upvotes: 1

Gaurav
Gaurav

Reputation: 81

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

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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

Upvotes: 3

Related Questions