Converting Json to Hashmap [duplicate] - java

This question already has answers here:
How to convert a JSON string to a Map<String, String> with Jackson JSON
(11 answers)
Closed 6 years ago.
I have a json string
{
{
key1:[values1]
},
{
key2:[values2]
}
}
I want to convert it into HashMap(String,Object) in java.
I have been using normal json parsing, where I create a jsonObject from the json string and extract jsonArrays from the jsonObject. Is there any direct API to convert it?

Always use jackson for JSON manipulation.
Check this out for other useful examples:
https://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
Regarding your question:
public class JsonMapExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":29}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
System.out.println(map);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap`

From one project I send data to another project.
I have my data in LinkedHashMap.
When I send, I convert map in Json:
objectMapper.writeValueAsString(visitToInsurer)
When I try to convert json value to map, I do:
T getJsonMessage(byte[] body) throws IOException {
return objectMapper.readValue(body, resolveGenericType());
}
Class<T> resolveGenericType() {
Class<?>[] tClass = GenericTypeResolver.resolveTypeArguments(getClass(), SomeClass.class);
return (Class<T>) tClass[0];//here i get interface of Map
}
And then I got an error:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of java.util.LinkedHashMap (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value
('{"id":1,"id2":2,"bDate":"2020-04-04T16:22:45.032087","eDate":"9999-12-31T00:00","cDate":"2020-04-04T16:22:45.032087","use":"1","act":true,"in":0,"vDt":null,"vDt2":null,"dCheck":null,"vFlag":true,"nFlag":false,"vFlag2":false,"nFlag2":false,"uFlag":true,"rFlag":false,"dId":1,"it":1,"rId":1,"rCode":"1","iNum":"1","iAb":"OOO\"TEST-1 \"TEST\"","dId3":2,"dId4":2,"dName":"Test","vId5":null,"vId6":null,"pDt7":null,"pDt8":null,"vDt9":null,"vDt10":null,"wCnt":null,"dId8":null,"dId9":null,"dName10":null,"dName11":"Test","cReason":null,"vd12":null,"vId13":null,"vNum14":null,"vDate15":null,"act":null,"rLst":[{"id":1,"id2":2,"bDate":"2020-04-04T16:22:45.236460","eDate":"9999-12-31T00:00","cDate":"2020-04-04T16:22:45.236460","user":"1","vId":1,"vId2":1,"dId":2,"dId2":2,"dName":"TTT","pDt":null,"pDt2":null,"vDt":null,"vDt2":null,"cBegin":"2020-05-04T00:00:00","cEnd":"2020-05-05T00:00:00","cNum":"111","amount":0,"amount2":0,"prem":0,"f":0,"pen":0,"dId5":1,"dName6":"Test","aFlag":false,"rId":11,"rCode":"11","cNum":0,"dId7":1,"pId8":null,"pId9":null,"act":null}],"vCard":{"id":1,"id2":1,"bDate":"2020-04-04T16:22:45.032087","eDate":"9999-12-31T00:00","cDate":"2020-04-04T16:22:45.032087","user":"1","act":true,"invalid":0,"rId":1,"rCode":"1","iName":"TEST \"TEST \"TEST\"","iName2":"TEST\"TEST \"TEST\"","rNum":"1","in5":"1","k77":"1","og77":"11","rBegin":"2009-09-28T00:00:00","inDate":"2009-09-28T00:00:00","outDate":null,"phone":null,"localAddress":"TEST","email":null,"iStatus":"State","sCode":"1","iCode":"1","oCode":"1","cBegin5":"1900-01-01T00:00:00","pName":null,"pName2":null,"pReg":null,"action":null,"vList":[{"id":1,"id2":"1","cCode":"1","vId":1,"vId2":1,"bDate":"2020-04-04T16:22:45.032087","eDate":"9999-12-31T00:00","cDate":"2020-04-04T16:22:45.032087","user":"1","actual":true,"rId":1,"rCode":"1","came":"ТTEST","cPhone":null,"cP":"TEST","action":null}],"vList2":[]},"vList3":[{"id":1,"id2":1,"bDate":"2020-04-04T16:22:45.095369","eDate":"9999-12-31T00:00","cDate":"2020-04-04T16:22:45.095369","user":"1","actual":true,"vId":1,"vId":1,"tNum":"1","surname":"TEST","name":"TEST","pat":"TEST","pName2":"TEST","phone":null,"kId":1,"kId2":1,"vChecks":"TEST","nFlag":false,"vFlag":true,"nFlag2":false,"vFlag2":false,"action":null}],"vList5":[]}')
UPDATE:
Thank you all. Problem was in my code where I send message from producer to subscriber. I try to send json string in field for object, not in field for json string.
public class ProducerMsg {
private String body;
private Object objectBody;
}
So in dependency it doesnt't work because think that it is already Map(and I send String in which is Map)
Please refer below code
public class JsonToMapDemo {
public static void main(String[] args) {
String json = "{\"name\":\"Akshay\",\"age\":\"23\"}";
convertJsonToMap(json);
}
private static void convertJsonToMap(String jsonString) {
try {
Map<String, Object> personMap = new ObjectMapper().readValue(jsonString, Map.class);
/*
If we need LinkedHashMap Object
LinkedHashMap personMap = (LinkedHashMap) new ObjectMapper().readValue(jsonString, Map.class);
*/
System.out.println(personMap);
}
catch (JsonGenerationException e)
{
e.printStackTrace();
}
catch (JsonMappingException e)
{
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
code output
{name=Akshay, age=23}

Java Nashorn build json array object in java can't find way

I try to create java json array ,
can't find any way to create them using Nashorn
i can create simple objects ...
private void createJsonObject() {
try {
final Map<String, Object> newMap = new HashMap<>();
newMap.put("foo",1);
newMap.put("bar", true);
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.putAll(newMap);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result : {"bar":true,"foo":1}
Here i try to create array but im getting empty json
private void createJsonObject() {
try {
List<String> returnList = new ArrayList<>();
returnList.add("x");
returnList.add("y");
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.put("test",returnList);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result: {}
The end goal is to build array of objects in memory using java native tools without using dependencies

Check if JSON fits the needed class using GSON

I have a class like
data class Data(
val field1: Int = 123
val field2: String = "Foo"
)
I have JSON like
{"field1": 123, "field2": "Foo"}
How can I check if my JSON really represents the structure of the class using Google GSON?
Hi bro there are several Ways first by using code
import org.json.*;
public boolean isValidJSONTest(String yourjsonString) {
try {
new JSONObject(yourjsonString);
} catch (JSONException ex) {
try {
new JSONArray(yourjsonString);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
For Gson code is like
Gson gson = new Gson();
try {
Object o = gson.fromJson(json, Object.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(o));
} catch (Exception e) {
System.out.println("invalid json format");
}
second you can use browser console and paste your string in console and enter
third they are several website that can validate json format or view etc
https://jsonlint.com/

How to parsing JSON like this?

I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}

Jackson serialize multiple objects into one

I've got an Ajax call to populate multiple fields in the front end from Hibernate Objects. That's why I would like to return multiple Java Hibernate to Json serialized objects to Ajax from Spring. Currently I do:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson()
{
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try
{
json = ow.writeValueAsString(result);
} catch (JsonGenerationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
This works fine and returns a json object to ajax but I have multiple objects like that so what I want is to nest all these objects in one json object and return the latter to my ajax so I can populate all fields using one object rather than making multiple ajax calls for each object I need. So for example I would to have something like:
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(result);
List<SecondObject> secondObject = serviceSecondObject.getSecondObject(pk);
String json2 = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json2 = ow.writeValueAsString(secondObject );
NewJsonObject.add(json)
NewJsonObject.add(json2)
return newJsonObject;
You should be able to just use a Map (since JSON Objects aren't anything different than a Map) to hold your objects:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson() {
Map<String, Object> theMap = new LinkedHashMap<>();
// if you don't care about order just use a regular HashMap
// put your objects in the Map with their names as keys
theMap.put("someObject", someModelObject);
// write the map using your code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
return ow.writeValueAsString(theMap);
}
You can now access all the objects in the Map in your JS, since the Map will get serialized as a JSON-Object:
response.someObject == { // JSON Serialization of someModelObject }

Categories