0

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
1
  • 2
    This isn't json. Remove the brackets. Replace the colon... Commented Feb 9, 2021 at 14:35

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Gson can't parse the above string and seems unnecessary overall
1

{name:yashav} this is not a valid JSON format. If you have {"name": "yashav"} you can use Jackson to parse JSON to java object.

class Person {
  String name;
  ...
}

ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue("{\"name\" : \"mkyong\"}", Person.class);

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.