Console print an array of objects with Jackson - java

I have a method that exports every POJO person and create an array into a JSON:
Node temp = testa;
ObjectMapper mapper = new ObjectMapper();
FileWriter fileWriter = new FileWriter(Paths.get("jPerson.json").toFile(), true);
SequenceWriter seqWriter = mapper.writer().writeValuesAsArray(fileWriter);
while (temp != null) {
seqWriter.write(temp.getPersona());
temp = temp.getSuccessivo();
}
seqWriter.close();
I want to create a method that read every object of the array and print it on the screen. This is the prototype, but it prints the hashcode (Person#6a1aab78, etc.):
ObjectMapper mapper = new ObjectMapper();
try {
Persona[] pJson;
pJson = mapper.readValue(Paths.get("jPersona.json").toFile(), Persona[].class);
System.out.println(ReflectionToStringBuilder.toString(pJson));
} catch (IOException e) {
e.printStackTrace();
}

ReflectionToStringBuilder.toString(Object) doesn't create a "deep" toString method. In your case you could just call Arrays.toString(pJson) and it would have the same result.
Easiest solution is to just override toString in Persona.
public class Persona {
#Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
System.out.println(Arrays.toString(pJson));
Or you use a Stream to join all the values in the pJson array to one String.
System.out.println('[' + Arrays.stream(pJson)
.map(ReflectionToStringBuilder::toString)
.collect(Collectors.joining(", "))+']');

You can do it with ObjectMapper.
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pJson);
System.out.println(json);
Reference: https://mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/

If you want to print your POJO Persona as JSON, you can use Jackson's ObjectMapper to serialize to a JsonNode and use JsonNode#toString():
final Persona persona = ...;
final JsonNode json = objectMapper.readValue(persona, JsonNode.class);
System.out.println(json);
If you want to print multiple Persona objects, you can iterate:
for(final Persona persona : personas) {
final JsonNode json = objectMapper.readValue(persona, JsonNode.class);
System.out.println(json);
}
or, even better, serialize once and iterate:
final Persona[] personas = ...;
final JsonNode jsonArray = objectMapper.valueToTree(personas);
// Check may not be necessary.
if(json.isArray()) {
// JsonNode implements Iterable.
for(final JsonNode jsonNode : jsonArray) {
System.out.println(jsonNode);
}
}

Related

how to read an array of object from json using gson?

I've written a file JSON with the information that I need to use to create an array
This is the json that I'm using
[{
"matr": [0,0],
"room": "b",
"door": true,
"respawnPoint": false
},
{
"matr": [0,1],
"room": "b",
"door": false,
"respawnPoint": false
},...
]
and this is how I try to de-serialize it with java
String path="src/main/resources/room.json";
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(path,
SupportPosition[].class);
but this error appears
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
You are passing the file path as a parameter into the Gson constructor.
You must pass the JsonReader object into the Gson constructor as a parameter.
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);
try this and let me know.
Parsing JSON array into java.util.List with Gson I think your question has already been answered in a different post. Take a look into it.
public class Human {
String name;
Integer age;
//getters and setters
}
Main class is below :
public class Solution{
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"Dummy\", \"age\":37}, {\"name\":\"Dummy2\", \"age\":38}]";
try {
// 1. convert JSON array to Array objects
Human[] HumanObjects = mapper.readValue(json, Human[].class);
System.out.println("JSON array to Array objects...");
for (Human Human : HumanObjects) {
System.out.println(Human);
}
// 2. convert JSON array to List of objects
List<Human> ppl2 = Arrays.asList(mapper.readValue(json, Human[].class));
System.out.println("\nJSON array to List of objects");
ppl2.stream().forEach(x -> System.out.println(x));
// 3. alternative
List<Human> pp3 = mapper.readValue(json, new TypeReference<List<Human>>() {});
System.out.println("\nAlternative...");
pp3.stream().forEach(x -> System.out.println(x));
} catch (Exceptoion e) {
e.printStackTrace();
}
}
}
Use need to import "Jackson". Probably add a Maven dependency. Let me know if it helps.

Unable to Convert String into JSON using Java

I am getting a json from rest call as {"d1":1, "d2":1, "d3":0, "d4":1} which is stored in db as - {d1=1, d2=1, d3=0, d4=1}.
When I am reading from database i am getting the above as string as - {d1=1, d2=1, d3=0, d4=1}. I want to convert this to its original form as before like - {"d1":1, "d2":1, "d3":0, "d4":1} mentioned above.
How can i achieve this in java. is there any json library available to do this ?
Sofar I have tried this but it didn't worked out -
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);
I want to put this json in ResponseEntity>.
Even I tried -
jsonString = jsonString.replaceAll("=", ":");
JSONObject jsonObject = new JSONObject(jsonString);
String finalJsonString = jsonObject.toString();
This is giving back response as "{\"d1\":1, \"d2\":1, \"d3\":0, \"d4\":1}" with double quotes in the begining and ending with backslashes before double quotes for keys.
The String returned through DB is not in JSON format, so parsing fails.
You could use the following approach to format the returned string into a JSON string, and then parse it.
I have used Guava's Splitter.MapSplitter:
String in = "{d1=1,d2=1,d3=0,d4=1}";
in = in.replaceAll("[{}]", "");
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator("=").split(in);
JSONObject obj = new JSONObject(properties);
String formattedString = obj.toString();
The string that you are retrieving from DB is a Map data structure. So you can convert a Map to JSON as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
Edited
The following code snippet will provide you the complete JSON response.
#RestController
#RequestMapping("/api/v1/")
public class TestController {
#GetMapping(value="test",produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> test() {
Map<String,String> payload = new HashMap<>();
payload.put("d1","value1");
payload.put("d2","value2");
payload.put("d3","value3");
payload.put("d4","value4");
String json =null;
try {
json= new ObjectMapper().writeValueAsString(payload);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new ResponseEntity(json,HttpStatus.OK);
}
}
Postman test:
You can do as follows :
ObjectMapper mapper = new ObjectMapper();
try {
MyResponse result = mapper.readValue(e.getResponseBodyAsString(),MyResponse.class);
return result;
} catch (IOException e1) {
e1.printStackTrace();
}

JSON string to Object[]

I need to convert JSON string to Object[].
I tried with link1 and link2 and did not help me.
Code how i get JSON string:
public static String getListJsonString() {
String getListsUrl = BASE_URL + "lists";
String result = "";
try {
URL url = new URL(getListsUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + getAuthStringEnc());
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
result = sb.toString();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
This is example of my JSON:
And after i must fill ChomboBox on this way (this is example):
Object[] lists = getLists();
for(Object list : lists){
System.out.println("fill combobox");
}
You can use Gson, TypeToken and JSONObject, example:
final static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
final Type objectType = new TypeToken<Object>(){}.getType();
JSONObject obj = new JSONObject(result);
Vector<Object> lists = gson.fromJson(obj.toString(), objectType);
I suggest you should be using jackson lib. I linked a great quick tutorial that I find really clear and useful.
The idea behind jackson lib is that JSON format is a stringified Object format so you should be able to map it properly to java POJOs easily. (POJO = Plain old java object, which is an object with some fields, maybe some annotations on top of your fields and finally just getters and setters).
You can auto generate Jackson annotated POJOs classes from a json string using this link : http://www.jsonschema2pojo.org/ (just select "JSON" instead of "JSON SCHEMA", and maybe tune the other parameters depending on your need).
I can feel your pain sometimes it's hard to get a quick example up and running.
This is a very simple example how you can read your json document using Jackson library. You need a minimum of jackson-annotations-x.y.z.jar, jackson-core-x.y.z.jar and jackson-databind-x.y.z.jar files in a classpath.
https://github.com/FasterXML/jackson-databind/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class TestJSON1 {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj;
String jsonStr = "{ \"list\": [ "
+ " {\"id\":\"1\", \"name\":\"test1\"}, "
+ " {\"id\":\"2\", \"name\":\"test2\"}, "
+ " {\"id\":\"3\", \"name\":\"test3\"} "
+ "]}";
jsonObj = mapper.readTree(jsonStr);
System.out.println(jsonObj.get("list"));
JsonNode jsonArr=jsonObj.get("list");
int count=jsonArr.size();
for (int idx=0; idx<count; idx++) {
jsonObj = jsonArr.get(idx);
System.out.println( jsonObj.get("id").asText()+"="+jsonObj.get("name").asText() );
}
}
}

how to achieve string conversion of list of maps in java

How can i convert JSON string to format given below and back to JSON string.
List<Map<String, String>> variables =new ArrayList<>();
I tried searching for this. Only thing which i could find is converting list to array and then to string. But using
TypeA[] array = a.toArray(new TypeA[a.size()]);
does not seems feasible here.
Converting List<Map<String,String>> to JSON string :
public String listmap_to_json_string(List<Map<String, String>> list)
{
JSONArray json_arr=new JSONArray();
for (Map<String, String> map : list) {
JSONObject json_obj=new JSONObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
try {
json_obj.put(key,value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json_arr.put(json_obj);
}
return json_arr.toString();
}
Or simply using google gson library:
public String listmap_to_json_string(List<Map<String, String>> list){
// Use toJson method to serialize list to Json
return new GsonBuilder().setPrettyPrinting().create().toJson(list);
}
Converting JSON string to List<Map<String,String>>:
public List<Map<String, String>> json_string_to_listmap(String json){
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
// Use fromJson method to deserialize json into an ArrayList of Map
return gson.fromJson(json , type);
}
For more informations check this link.
Indeed you should update your question to give more details. Meanwhile, with the current understanding I have from your post I would suggest you to look at ObjectMapper class from org.codehaus.jackson.map.
You will easily get a JSON converted in the type you want by using
// string in json format
String json;
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, TypeA.class);
This code show how convert json string to type List<Map<String,String>>:
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference < List < Map < String, String >>> typeReference = new TypeReference < List < Map < String, String >>> () {
};
List < Map < String, String >> res = objectMapper.readValue("[{\"size\":\"100x200\"}]", typeReference);
System.out.println("type: " + typeReference.getType());
for (Map < String, String > map: res) {
for (String key: map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
}
} catch (IOException e) {
e.printStackTrace();
}

Reading individual JSON events using Jackson

I have a file with several JSON objects, each of which may contain other objects and arrays.
I would like to deserialize this, preferably using the Jackson library, into a data structure that maintains top-level object separation, e.g. an array or a list of Java HashMap<String, String> objects, where each HashMap will contain the data of a single top-level JSON object from the file.
From what I have seen, you can't get a HashMap<String, String> from Jackson, so I have to put up with a HashMap<String, Object>:
List<HashMap<String,Object>> values = new ObjectMapper().readValue(new BufferedReader(new FileReader(path)), new TypeReference<List<HashMap<String, Object>>>() {});
The deserialization above works as expected, however I get all the file data and a not a single JSON object's data, as I would like.
Any ideas?
Thanks!
After quite a bit of effort, here is a simple approach that seems to work:
Reader inputReader = new BufferedReader(new FileReader(filename));
int readEvents = 0;
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createJsonParser(inputReader);
JsonToken token = null;
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Object> attributes = null;
ArrayList<Map<String,Object>> matchedEvents = new ArrayList<Map<String,Object>>();
try
{
while ((token=parser.nextToken()) != null)
{
if (token == JsonToken.START_OBJECT)
{
readEvents++;
attributes = mapper.readValue(parser,
new TypeReference<HashMap<String, Object>>() {});
if (attributes != null)
{
matchedEvents.add(attributes);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Read " + readEvents + " events");
Each of the HashMap<String, Object> objects placed in the above ArrayList corresponds to a single (top-level) JSON event.
The readValue() methods apparently do not return a Map(String, String) object.

Categories

Resources