Skip to content

Instantly share code, notes, and snippets.

@felipebizz
Created June 8, 2016 22:03
Show Gist options
  • Save felipebizz/6c06be52bbacaeb56dfce76b886b15b7 to your computer and use it in GitHub Desktop.
Save felipebizz/6c06be52bbacaeb56dfce76b886b15b7 to your computer and use it in GitHub Desktop.
Convert Json to Map and Map to Json
package global.visto.tasks.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Classe responsavel por fazer a conversao de HashMap para Json e vice-versa
*/
@Service
public class Convert {
/**
* Convert a Map into JSON string.
*
* @param map map de atributos
* @return json String
*/
public String mapToJson(Map<String, String> map) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
return json;
}
/**
* Convert a Json to map
*
* @param json string json
* @return Map de atributos
*/
public Map<String, String> jsonToMap(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
return map;
}
public static void main(String[] args) throws IOException {
Convert convert = new Convert();
Map personMap = new HashMap<>();
Map personDetail = new HashMap();
personDetail.put("firstname", "Felipe");
personDetail.put("lastname", "Lima");
personDetail.put("age", "32");
personDetail.put("city", "Sao Paulo");
personMap.put("person", personDetail);
final String json = convert.mapToJson(personMap);
System.out.println("json = " + json);
final Map<String, String> map = convert.jsonToMap(json);
System.out.println("Map is " + map);
// convert json to Map
String json2 = "{\"person\":{\"age\":\"32\",\"lastname\":\"Lima\""
+ ",\"firstname\":\"Felipe\",\"city\":\"SaoPaulo\"}}";
String json3 = "{\"processVariablesValueEquals\":{[\"fixedvarJobId\":\"501\"]}\"}";
final String s2 = "{\"processVariablesValueEquals\":[{\"fixedvarJobId\":\"501\"}]}";
final String s3 = "{\"processVariablesValueEquals\":[{\"fixedvarJobId\":\"501\",\"name\":\"teste\"},{\"fixedvarJobId\":\"502\",\"name\":\"teste2\"}]}";
System.out.println("Map2 is : " + convert.jsonToMap(s2));
System.out.println("Map3 is : " + convert.jsonToMap(s3));
System.out.println("JSON3 is : " + convert.mapToJson(convert.jsonToMap(s3)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment