2

I am dealing with json data fetched from twitter API

on PHP I normally do something like:

$data = json_decode($response); and the $data would be STD class object

I want to do the same thing in Java.

I took a look at Gson, but I need a second argument which seems like I need to create a specific class for the fetched data.

The basic question is how can I convert JSON to Standard Java Object like in PHP (STD Class Object)

Thank You

4 Answers 4

6

Read it into a map using Jackson then you can access whatever data you want. For instance, if your json looks like this

{ "name":"blah",
  "address": {
    "line1": "1234 my street",
    "city": "my city",
    "state": "my state"
  }
}

Then you could:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mystuff = mapper.readValue( jsonString, Map.class );
String name = (String)mystuff.get("name");
String city = ((Map<String, Object>)mystuff.get( "address" )).get( "city" );
Sign up to request clarification or add additional context in comments.

3 Comments

this seems simple. I will try this
I'm using this in a couple of unit tests where I'm testing code that produces JSON and it works well. It is pretty simple and Jackson is fast.
String city = ((Map<String, Object>)mystuff.get( "address" )).get( "city" ); gave me an issue that it was an object, not a string. added .toString() to fix it
3

If your JSON data does not follow a specific structure, don't use GSON, but a regular JSON library (like the one from json.org) that will give you an instance of a class like JSONObject, from which you can access data like jsonObject.getString("key").

5 Comments

+1 json.org - simple and sufficient in most cases (added the link to json.org on your answer - hope you dont mind)
this can solve the problem, but how can I access a nested object inside the object?
@bn - by calling jsonObject.getObject("key"). Read the javadocs.
How do you want to get an object if you don't want to have a class? Maybe I didn't understand your initial question
for example i want to access nested object like this in PHP $data->resultset->result->username. How can I do this in Java?
0

There is no standard class object in Java and thus you need a class. You could dynamically create and compile the class at runtime but I doubt that's worth the trouble.

Comments

-1

When json_encode doesn't exist on a PHP server, I use this:

<?php
if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}
?>

If you could rewrite this in Java then it should to the trick for you.

Ref:(Dead link)http://snippets.dzone.com/posts/show/7487

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.