Convert JSON to Map

Convert JSON to Map

I hope you were joking about writing your own parser. :-)

For such a simple mapping, most tools from http://json.org (section java) would work.
For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:

Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String)

Convert a JSON String to a HashMap

In recursive way:

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();

if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();

Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);

if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}

else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}

public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}

else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}

Using Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;

Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);

convert json to array/map

in your code this.props.json is not an array, it's an array-like object and map is an array function. what your doing to solve this, is converting that array-like object into an array, with .slice()

a more elegant way to do this:

Array.from(this.props.json).map(row => <RowRender key={id.row} row={row} />)

How to convert hashmap to JSON object in Java

You can use:

new JSONObject(map);

Other functions you can get from its documentation

http://stleary.github.io/JSON-java/index.html

how to convert json to list/map with jackson

You can use Jackson ObjectMapper with TypeReference ,
First you need to read it as Map<String,Object> then you can extract the name and num with Java.

you need to get the data from obj then for each item in the dataList you have to map it to a new HashMap as shown below

ObjectMapper objectMapper = new ObjectMapper ();
Map<String,Object> jsonMap = objectMapper.readValue(jsonData,new TypeReference<Map<String,Object>>(){});
List<Object> data = ((Map<String,Object>)jsonMap.get("obj")).get("data");
List<Map<String,String> result = data.stream()
.map(d->(Map<String,Object> d)
.map(d->{
Map<String,String> map = new HashMap();
map.put(d.get("name"),((Map<String,String>)d.get("value")).get("num"));
return map;
})
.collect(Collectors.toList());

However if you can create a class for the the data it will be bit easier.

Convert JSON data to List Map String, dynamic

You need to cast your json like this:

var rawJson = '[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';

List<Map<String, dynamic>> output = (json.decode(rawJson) as List).cast();
// or
List<Map<String, dynamic>> output = List.from(json.decode(rawJson) as List);

Java code to Convert JSON into a Map with specific fields as Key and values

You can use jackson for example:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>

I would create a wrapper for the resulting Map and a custom deserializer.

@JsonDeserialize(using = MapWrapperDeserializer.class)
public class MapWrapper {

private final Map<String, String> map;

public MapWrapper(Map<String, String> map) {
this.map = map;
}

public Map<String, String> getMap() {
return this.map;
}
}

The deserializer:

public class MapWrapperDeserializer extends StdDeserializer<MapWrapper> {

public MapWrapperDeserializer() {
super(MapWrapper.class);
}

@Override
public MapWrapper deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode array = parser.getCodec().readTree(parser);
int size = array.size();
Map<String, String> map = new LinkedHashMap<>(size);
for (JsonNode element : array) {
String key = element.get("a").asText();
String value = element.get("c").asText();
map.put(key, value);
}
return new MapWrapper(map);
}
}

A simple test:

public class Temp {

public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
InputStream dataStream = getInputStreamOrJsonString();
MapWrapper wrapper = mapper.readValue(dataStream, MapWrapper.class);
System.out.println(wrapper.getMap());
}
}


Related Topics



Leave a reply



Submit