Convert Java String to HashMap Object - java

I have created an application for converting the HashMap object to String, its working fine, The problem which i am facing is that i want to convert the HashMap string again back to HasMap object, when i tried that by using the following code , I am getting exception as shown below
Unexpected character ('u' (code 117)): was expecting double-quote to start field name
Can anyone please tell me some solution for this
My code is given below
Map<String,Object> map = new HashMap<String,Object>();
map.put("userVisible", true);
map.put("userId", "1256");
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(map.toString(), new TypeReference<HashMap<String,Object>>(){});
System.out.println(map.get("userId"));
} catch (Exception e) {
e.printStackTrace();
}
Update 1
As suggested by #chrylis I have used Feature.ALLOW_UNQUOTED_FIELD_NAMES like as shown below, but now i am getting the following exception
Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value
Updated Code
Map<String,Object> map = new HashMap<String,Object>();
map.put("userVisible", true);
map.put("userId", "1256");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
try {
map = mapper.readValue(map.toString(), new TypeReference<HashMap<String,Object>>(){});
System.out.println(map.get("userId"));
} catch (Exception e) {
e.printStackTrace();
}

You're getting this error because JSON specifies that you have to put field names in quotation marks, unlike in a regular JavaScript object. You can tell Jackson to permit unquoted field names by configuring the ObjectMapper so:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Update
It appears that a more fundamental problem is that you're trying to use Java toString() to convert the map to a String, and a Jackson JSON mapper to convert it back. The two are completely different formats, and if you need to be able to convert the string back into an object, you should probably use the Jackson mapper to turn the map into JSON in the first place.

Related

get a key value pair from a String json (simple object)

Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github

How can I somehow "store" a json file in a Spring-Boot program so my web app then reads this json

Basically, I'm writing my first Spring-Boot program, and I have to get a list of products stored on a JSON file to display each product using VueJS (I know how to use Vue, I just need to get the JSON data somewhere in the webpage or smth)
I spent last 3'5 hours looking at tutorials about consuming JSON's and POST stuff and none helped.
Lets call your file config.json.
In a typical maven project, keep your file at
src/main/resources/config.json
In your code, read it like
try {
ClassPathResource configFile = new ClassPathResource("config.json");
String json = IOUtils.toString(configFile.getInputStream(), Charset.forName(Util.UTF_8));
} catch (IOException e) {
String errMsg = "unexpected error while reading config file";
logger.error(errMsg, e);
throw new Exception(e);
}
After this, use Jackson or GSON to read the json into an object. From there you can either reference it directly as a static attribute or as an attribute in component as per your use case.
Hope this code will work for you
public class JsonReader{
public static void readFromJson() throws Exception {
InputStream inStream = JsonReader.class.getResourceAsStream("/" + "your_config_file.json");
Map<String, String> keyValueMap =
new ObjectMapper().readValue(inStream, new TypeReference<Map<String, String>>() {});
inStream.close();
}
}
You might need to add the maven dependency for ObjectMapper()

How to convert a POJO to Map<String, AttributeValue> for dynamo db?

I am using transaction for dynamodb. And transaction Put request takes com.amazonaws.services.dynamodbv2.document.Item as input param. So, I need to convert a POJO to a Map.
So far I have tried converting the object to string using Jackson and then converting the string to an item.
Below is the code I have tried.
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Item item = new Item().withJSON("document", jsonStr);
Map<String,AttributeValue> attributes = ItemUtils.toAttributeValues(item);
return attributes.get("document").getM();
Problem is, a field of 'Set' type returns 'List' after conversion.
Any suggestion how to overcome this?
Below code should solve your convertion:
Map<String, AttributeValue> valueMap = ItemUtils.toAttributeValues(item);
CustomEntity entity = dynamoDBMapper.marshallIntoObject(CustomEntity.class, valueMap);

Create json object of undefined content

I am working with an exiting API that expects a "Metadata" field as part of its json payload. That "Metadata" field is a json object that is completely free-form. Currently, I need to read this data provided from another source, do some enrichment, then pass it on. I am struggling with how to define this "Metadata" object so that it can be any valid json object. OR, if that field was not provided, an empty json object.
I attempted to use org.json.JSONObject like so.
//meta is the json string read from the db
JSONObject jsonobject = new JSONObject(meta);
message.Metadata = jsonobject;
However, jackson, not unexpectedly, threw a serialization error:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered...
This is a critical requirement that I'm guessing I am missing some relatively obvious solution to. Any help would be greatly appreciated.
UPDATED FIX
As suggested by #shmosel I just switched the json object to a com.fasterxml.jackson.databind.JsonNode and all works beautifully.
// working code (rough of course)
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = null;
try {
rootNode = mapper.readTree(meta);
} catch (IOException e) {
e.printStackTrace();
}
message.Metadata = rootNode;

Construct specific instance of ObjectWriter from the shared ObjectMapper in Jackson 2 to ignore null fields

I am working with Jackson 2 and CXF.
I have done lots of research to find a clean and safe way to get a writer object from the shared object mapper that is given to CXF for un/marshaling JSON. I cannot just use annotation or set the mapper object to ignore null fields when serializing due to some business logic.
The code below seem to be very correct, but the output JSON still include null fields. Please help !!
ObjectWriter writer = this.jacksonMapper.writer().without( SerializationFeature.WRITE_NULL_MAP_VALUES ) ;
if( writer.isEnabled( SerializationFeature.WRITE_NULL_MAP_VALUES ) ) {
System.out.println("Oppa gangname style");
}
String json = null;
try {
json = writer.writeValueAsString( myObject );
System.out.println ( json ) ;
} catch (JsonProcessingException e) {
throw new RuntimeException() ;
}
The if case verify that I have successful disable SerializationFeature.WRITE_NULL_MAP_VALUES.
However, the result is still include null fields.
I'm using an older Jackson version but this works for me:
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
return mapper.writeValueAsString(input);
The docs say SerializationFeature.WRITE_NULL_MAP_VALUES only applies to generating JSON strings from Map objects.

Categories

Resources