Hi Guys I'm new to programming. In my java code i have string like this.
String json ="{"name":"yashav"}";
Please help me out to print the values using pre-build java functions. Expected output should be like below
name=yashav
Hi Guys I'm new to programming. In my java code i have string like this.
String json ="{"name":"yashav"}";
Please help me out to print the values using pre-build java functions. Expected output should be like below
name=yashav
First of all its not JSON. If you want to work for actual JSON. There are many libraries which help you to transfer string to object. GSON is one of those libraries. Use this to covert object then you can use keys to get values. Or you can iterate whole HashMap as per your requirements. https://github.com/google/gson
Forst of all, given String is NOT a json. It should be "{\"name\":\"yashav\"}". If you have a correct json string, you can use JacksonUtils.
Define a model:
class Url {
private String name;
public String getName() {
return name;
}
}
And parse the json string:
String json = "{\"name\":\"yashav\"}";
Url url = JsonUtils.readValue(json, Url.class);
System.out.format("name = %s", url.getName());
Another way is to use Regular Expression:
public static void main(String... args) {
String url = "{name:yashav}";
Pattern pattern = Pattern.compile("\\{(?<key>[^:]+):(?<value>[^\\}]+)\\}");
Matcher matcher = pattern.matcher(url);
if (matcher.matches())
System.out.format("%s = %s\n", matcher.group("key"), matcher.group("value"));
}
And finally, you can use plain old String operations:
public static void main(String... args) {
String url = "{name:yashav}";
int colon = url.indexOf(':');
String key = url.substring(1, colon);
String value = url.substring(colon + 1, url.length() - 1);
System.out.format("%s = %s\n", key, value);
}