How Singleton Save Me From Out of Memory Error

Hi there, long time I don’t talk about something more “techies” (not that Techies from Dota 2). I’ve been working on an Android Project and I want to talk about one library I’ve used extensively: Google GSON. The particular usage of GSON is to simplify the painful method of processing JSON object in Java.

Introduction to GSON

Consider this JSON as string:

{ 'id': 'EdgarDrake',
  'name': 'Edgar',
  'games': [
    { 'id': 'bethsw-bethgs-esv-skyrim',
      'name': 'The Elder Scrolls V: Skyrim',
      'price': 60,
      'meta': {
         'publisher': 'Bethesda Softworks',
         'developer': 'Bethesda Game Studio',
         'avg_rating': 4.8
       }
    },
    { 'id': 'ncsoft-arenanet-gw2',
      'name' : 'Guild Wars 2',
      'price': 45,
      'meta': {
         'publisher': 'NCSoft',
         'developer': 'ArenaNet',
         'avg_rating': 4.3
       }
     }
   ]
}

In Python, you can feed that JSON to variable and directly deserialize it to dictionary. Easy. Dead simple. Say, assign a variable called user with that JSON.

Q1: How to get user’s second game publisher name?

Q2: How to generate JSON string a new user Regulus who has game Destiny?

In Python, it’s as easy as:

// Q1
user.games[1].meta.publisher
// Q2
usr2 = {name:"Regulus",
        id:"0284R1R2L1L2",
        games:[
          {id:"actvsn-bungie-destiny",
           name:"Destiny",
           price:45,
           meta: {publisher:"Activision",
                  developer:"Bungie",
                  avg_rating:3.0}
        ]
       }
usr2.toString()

How do you do that in Java?  Continue reading

Advertisements