How to print information that is in json format but is printed in a way that allows the user to read?

Asked

Viewed 255 times

2

The application is printing in this json format but I don’t want it to print like this. For example I just want you to print "Translation": "Hi dear" and only. I am using eclipse and the java server language, as it does?

I am using an API but need to show the data I get from this api when I put to print with System.out.println(result);

It’s printing that way:

 {
   "character_count": 8,
  "translations": [
{
  "translation": "Oi querida"
}
],
 "word_count": 2
}
  • help me, please help me.

  • 1

    See if this helps: http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java

  • 1

    No negativei, you need to convert this string into a hashmap or another structure/type and then manipulate it. put the code you have.

  • 1

    The question sounds like "do for me the conversion of this json". Add what you’ve tried, and, as @rray said, set a more objective title to the problem.

  • I haven’t been able to do that yet......

1 answer

2


the best way to do this would be to structure your JSON string, that is to include it in some data structure to be able to access/modify its values in a simpler way, so I would use a library to transform a JSON string into an object, this being for example a Map or your own object to represent this JSON, follows a library more reference code for you to use that would solve this problem.

The name of the library is Gson, it is maintained by google, and is very popular in the Java world.

Example code:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());
System.out.println(map.get("k1")); //Saida = v1

References.

Repository on github: https://github.com/google/gson

Documentation: https://github.com/google/gson/blob/master/UserGuide.md

  • in my returns null.

  • probably your json is invalid or without the escape characters. Use this site http://jsonlint.com/ to validate your JSON and put the escape characters I didn’t even put there in the example. Then if you still have a problem send me JSON.

  • Oops I got it.

  • Show man, good studies there :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.