Monday, June 04, 2018

JSON to objects in a few languages

When working with data services, we often have a need to convert JSON strings to objects that model our data. Here is a list of code snippets in different languages that convert this Facebook Graph JSON data.

The list is presented in ascending order of verbosity. Predictably, Javascript most succinctly expresses its wishes, whereas Java uses a copious amount of code. Scala avoids some of that verbosity by using case classes that remove boilerplate code for constructors. Jackson (Java) requires getters and setters to identify which attributes of the object are to be serialized, causing code bloat.

JSON:
jsonbblob = """
{
"data": [
{
"created_time": "2017-12-08T01:08:57+0000",
"message": "Love this puzzle. One of my four coke puzzles",
"id": "820882001277849_1805191182846921"
},
{
"created_time": "2017-12-07T20:06:14+0000",
"message": "You need to add grape as a flavor for Coke in your freestyle machines.",
"id": "820882001277849_1804966026202770"
},
{
"created_time": "2017-12-07T01:29:12+0000",
"message": "Plz play the old commercial’s with the polar bears. Would be nice to see them this holiday",
"id": "820882001277849_1804168469615859"
}
]
}"""
view raw jsonblob hosted with ❤ by GitHub
Javascript:
var obj = JSON.parse(s)
for (var i = 0; i < obj.data.length; i++) {
var item = obj.data[i];
console.log(`created time ${item.created_time}, message ${item.message} id ${item.id}`)
}
view raw json-js hosted with ❤ by GitHub
Ruby:
require 'json'
require 'ostruct'
json_object = JSON.parse(json_string, object_class: OpenStruct)
json_object.data.each {
|d| puts "created time: %s message: %s id: %s" % [d.created_time, d.message, d.id]
}
view raw json-ruby hosted with ❤ by GitHub
Python:
import json
jb = json.loads(jsonbblob)
from collections import namedtuple
print (jb['data'][0].keys())
Puzzle = namedtuple('Puzzle', jb['data'][0].keys())
puzzles = [Puzzle(*puz.values()) for puz in jb['data']]
for p in puzzles:
print (p)
view raw json-py hosted with ❤ by GitHub
Scala:
import net.liftweb.json._
case class Puzzle(created_time: String, message: String, id: String)
case class PuzzleData(data: List[Puzzle])
implicit val formats = DefaultFormats
val parsed = puzzle_data.extract[PuzzleData]
for {
puzzle <- parsed.data
} yield println(puzzle)
view raw json-scala hosted with ❤ by GitHub
Java:
// PuzzleList.java
import java.util.Iterator;
import java.util.List;
public class PuzzleList implements Iterable<Puzzle> {
private List<Puzzle> data;
public PuzzleList() {
super();
}
public PuzzleList(List<Puzzle> data) {
this.data = data;
}
public List<Puzzle> getData() {
return this.data;
}
public void setData(List<Puzzle> data) {
this.data = data;
}
public Iterator<Puzzle> iterator() {
return data.iterator();
}
}
// Puzzle.java
public class Puzzle {
private String created_time;
private String message;
private String id;
public Puzzle() {
super();
}
public Puzzle(String created_time, String message, String id) {
this.created_time = created_time;
this.message = message;
this.id = id;
}
public String toString() {
return String.format("created_time: %s, message: %s, id: %s", this.created_time, this.message, this.id);
}
public String getCreated_time() {
return this.created_time;
}
public void setCreated_time(String created_time) {
this.created_time = created_time;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
//Main.java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
ObjectMapper mapper = new ObjectMapper();
try {
PuzzleList puzzles = mapper.readValue(jsonblob, PuzzleList.class);
for (Puzzle puzzle: puzzles) {
System.out.println(puzzle);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
view raw json-java hosted with ❤ by GitHub