How to use GSON with no names? - java

I am using GSON to decrypt some JSON that I get from a PHP site, with the layout of:
[{"bellname":"Hey!","date":"2013-09-11"},{"bellname":"Haaaaey!","date":"2013-09-01"}]
I want to put this into a HashMap, and have seen that I need to create a class to do this. That is the part that I do not understand. This is what I have so far:
public class MySQLDB {
private BellName bellName;
private BellDate bellDate;
public static class BellName {
private String bn;
}
public static class BellDate {
private String date;
}
}
Where would I go from here? If you need to see my PHP code, here it is:
<?php
mysql_connect("localhost", "*******", "******");
mysql_select_db("tests");
$q1 = mysql_query("SELECT `bellname`, `date` FROM `bells`");
if($q1) {
$que1 = array();
while($a1 = mysql_fetch_assoc($q1)) {
$que1[] = $a1;
}
$json1 = json_encode($que1);
echo $json1;
}
?>
All this PHP code does is put a "mysql_fetch_assoc" reply into JSON.
Please help, if you could tell me how to fix this?
Thanks.

public class MySQLEntry {
public String bellname;
public String date;
}
// ...
Gson gson = new Gson();
MySQLEntry[] entryArray = gson.fromJson(yourJsonString, MySQLEntry[].class);

Answer by jpossi is the most appropriate. But just for you to know json object could be represented as Map in Java. And json array could be represented as List. So in your case you also can do this:
Gson gson = new Gson();
Type type = new TypeToken<List<Map<String,String>>>(){}.getType();
List<Map<String, String>> value = gson.fromJson("[{\"bellname\":\"Hey!\",\"date\":\"2013-09-11\"},{\"bellname\":\"Haaaaey!\",\"date\":\"2013-09-01\"}]", type);
System.out.println(value);
But deserializing in object is better then deserializing in collection of Strings in most cases.

Related

Gson - Convert from json string to list of objects

I have a JSON string of the format:
resp = '{"result": [{x: 1, y:2}, {x:3, y:4}]}'
I want to convert the data from "result" key into list of objects. Something like:
List<MyCustomObj> data = new Gson()
.fromJson(resp, new TypeToken<ArrayList<MyCustomObj>>(){}.getType());
Is there a way to specify in above statement to fetch from the key "result"?
Just create a DTO that describes the structure of JSON, like:
#Getter #Setter
public class Response {
#Getter #Setter
public static class MyCustomObject {
private int x;
private int y;
}
private List<MyCustomObject> result;
}
Then it is just:
Response resp = gson.fromJson(json, Response.class);
List<MyCustomObject> result = resp.getResult();
It might be a good idea to keep the JSON format and the data structure in sync instead of some special parsing. There might not be any performance boost gained.

Is there a way to read a string into the Jackson API to easily get back a JSON object

Is there was a way to pass a String into some Jackson object and have it populate the JSON obj for me? Maybe I'm comparing apples to oranges but the json-rpc-1.0.jar library allows me to do this:
// string will be read in from file but putting the string below just to show what i'm trying to do.
JSONObject jsonObj;
String testStr = "{"blah":123, "aaa": "got here", "foo":"bar", "bar":123}";
jsonObj = new JSONObject(testStr);
jsonObj.put("blah",345);
If I execute
System.out.println(jsonObj);
I get:
{"blah":345, "aaa": "got here", "foo":"bar", "bar":123}
The problem with the json-rpc-1.0.jar file is it doesn't play nicely with long primitive types. For some reason, it converts long data to something like 1.32e9 if I tried to assign a timestamp (long data type) to a field.
I found Jackson (jackson-core-2.2.3.jar) is nicer to longs, preserving the 10-13 digits I need for my timestamp. However, I can't find anything that works like the above snippet of code in Jackson. The closest might be ObjectMapper.readValue but it's not exactly like above.
Please let me know if this is possible or if I'm just dreaming. Thanks in advance for your help. In the meantime, I will try to look at the API some more.
IMO this is not how Jackson is meant to be used. With Jackson, an object should be serialized with the fields of its class. You shouldn't be adding anything to that JSON afterwards. For the sake of the question, however, here's what you can do. Take for example
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
MyClass a = new MyClass();
ObjectNode node = mapper.<ObjectNode>valueToTree(a);
node.put("blah", "123");
System.out.println(node);
}
static class MyClass {
private String value = "some text";
private long timestamp = System.currentTimeMillis();
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
which prints
{"value":"some text","timestamp":1384233053765,"blah":"123"}
The valueToTree() method will convert your object into an ObjectNode which is kind of a tree that holds the various JSON elements. You can modify this ObjectNode by adding or removing elements. That is what we do with node.put("blah", "123");. It will add a Json object with name blah and value "123".

conversion of array list to json object string

I have a model class method which returns a list of objects which contains all the registered user details. I want to fetch the list resturned by all() method and convert the data into JSON object and pass it to the view like a string. How can I do this conversion of this array list to JSON object?
I was unable to do this by below:
ObjectMapper mapper = new ObjectMapper();
JSONObject json = new JSONObject();
JsonNodeFactory jsonnode = JsonNodeFactory.instance;
ObjectNode result = new ObjectNode(jsonnode);
for (int i = 0; i < list.size(); i++) {
json.put(list.get(i).fname, list.get(i));
System.out.println(json.get("fname"));
}
#Entity
class Mydata extends Model {
#Id
public Long Id;
public String fname;
public String lname;
public String city;
public String state;
/****************** READ/select OPERATION *****************/
public static Finder < Long, Mydata > finder = new Finder(Long.class, Mydata.class);
public static List < Mydata > all() {
return finder.all();
}
public static void createuser(Mydata user) {
user.save();
}
}
To convert ArrayList to Json, just download Open Source json utility from:
http://json.org/java/ or Jar file from here
And just do:
JSONArray jsonAraay = new JSONArray(your_array_list);
That's it
Note: You should have setter/getter in your POJO/MODEL class to convert arraylist to json
Don't bother with org.json, use Jackson all the way:
// list is a List<MyData>
final ObjectMapper mapper = new ObjectMapper();
final Map<String, MyData> map = new HashMap<>();
for (final MyData data: list)
map.put(data.fname, data);
final JsonNode json = mapper.valueToTree(map);
You could use all sorts of third party libraries like others here have suggested, or just use Play's own simplified methods for this (found in play.libs.Json) which works with Jackson objects, but it is integrated into the framework and requires a lot less code to use, for example:
JsonNode myJsonNode = Json.toJson(MyListObject); which converts the List to a JsonNode object, then use something like String jsonResult = Json.stringify(myJsonNode); to convert it into a string representation.
If you are using the JSON in a template, don't forget to wrap it in something like #Html(myJsonString) so it will not escape anything. Otherwise, if you are just outputting the pure JSON to the browser, a simple return ok(jsonResult); will work as Play will automatically set the content type.
Reference link: http://www.playframework.com/documentation/api/2.0/java/play/libs/Json.html
have you looked at this:
http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)
JSONObject.valueToString(<<your list of custom object>> OR <<objects>> OR <<map>>)
works just fine...there are some other methods on that lib, if you are interested....

Parsing JSON String as simple as possible with GSON

Using GSON, how can i return a single key from a Multidimensional Json String?
Here is the Multidimensional Json String:
{"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}
I want to return the "session_token" key value.
I'm trying this:
class app {
static class Response {
String session_token;
}
public void getSessionToken() {
String x = {"statusCode":0,"statusDescription":"OK","data":{"user":{"id":xxx,"company_id":xxx,"account_type":"5","enable_locations":true,"intuit_user_id":null,"nick_name":"xxx","is_owner":"1","enabled":"1"},"session_token":"xxx"}}
Response r = new Gson().fromJson(x, Response.class);
System.out.println(r.session_token);
}
}
But with this, my r.session_token returns null.
You would need to use Gson's JsonParser class directly and extract the data from the parse tree:
String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(myJsonString);
JsonObject jsonObject = element.getAsJsonObject();
String lastName = jsonObject.get("lastname").getAsString();
System.out.println(lastName);
That said, it's debatable whether this would save you any real time over:
(edited from comments below):
class App {
static class Response {
String lastname;
}
public static void main(String[] args) {
String myJsonString = "{\"name\":\"john\",\"lastname\":\"smith\"}";
Response r = new Gson().fromJson(myJsonString, Response.class);
System.out.println(r.lastname);
}
}
Gson will silently ignore the fact that there's more data in the JSON than you're interested in, and later on you might be interested in it, in which case it's trivial to add fields to your Response class.
Edit due to question changing:
You have a JSON object. It contains a field data whose value is an object. Inside that object you have a field session_token that you're interested in.
Either you have to navigate to that field through the parse tree, or you have to create Java classes that all will map to. The Java classes would resemble (at the bare minimum):
class Response {
Data data;
}
class Data {
String session_token;
}

How to convert HTTP Request Body into JSON Object in Java

I am trying find a Java lib/api that will allow me to turn the contents of a HTTP Request POST body into a JSON object.
Ideally I would like to use a Apache Sling library (as they are exposed in my container naturally).
The closest I've found it: org.apache.sling.commons.json.http which converts the header to JSON.
HTTP Post bodies are in the format; key1=value1&key2=value2&..&keyn=valueN so I assume there is something out there, but I havent been able to find it.
I may just have to use a custom JSONTokener (org.apache.sling.commons.json.JSONTokener) to do this if something doesn't already exist. Thoughts?
Thanks
Assuming you're using an HttpServlet and a JSON library like json-simple you could do something like this:
public JSONObject requestParamsToJSON(ServletRequest req) {
JSONObject jsonObj = new JSONObject();
Map<String,String[]> params = req.getParameterMap();
for (Map.Entry<String,String[]> entry : params.entrySet()) {
String v[] = entry.getValue();
Object o = (v.length == 1) ? v[0] : v;
jsonObj.put(entry.getKey(), o);
}
return jsonObj;
}
With example usage:
public void doPost(HttpServletRequest req, HttpServletResponse res) {
JSONObject jsonObj = requestParamsToJSON(req);
// Now "jsonObj" is populated with the request parameters.
// e.g. {"key1":"value1", "key2":["value2a", "value2b"], ...}
}
Jackson is also a good option - its used extensively in Spring. Here is the tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
I recommend trying Apache Commons Beanutils.
ServeltRequest request;
Map map = request.getParameterMap();
MyObject object = new MyObject();
BeanUtils.populate(object, map);
String json = object.toJSON() //using any JSON library
Sorry on making this an own answer but obviously my reputation doesn't allow me to simply add a comment to the answer How to convert HTTP Request Body into JSON Object in Java of maerics.
I would also iterate over the request params but instead of using an arbitrary json library use the JSONObject that is provided by sling. http://sling.apache.org/apidocs/sling6/org/apache/sling/commons/json/JSONObject.html
import org.json.JSONObject;
JSONObject json = new JSONObject(request.getParameterMap())
Use Gson. With this you can create class with private variables which represent the data you want : for example.
meta:{
name:"Example"
firstname:"Example2"
}
data:[
{
title:"ecaetra"
description:"qwerty"
}
...
]
Json Object could be retrieve like this :
public class RetrieveData {
private Meta meta;
private List<Data> data;
public Meta getMeta(){
return meta;
}
public List<Data> getData(){
return data;
}
}
public class Meta {
private String name;
private String firstname;
public String getName(){
return name;
}
public String getFirstName(){
return firstname;
}
}
public class Data {
private String title;
private String description;
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
And your instruction are simple. Content is the content of your Page, you can retrieve it with Asynctask.
Object o = new Gson().fromJson(Content, RetrieveData.class);
data = (RetrieveData)o;
// Get Meta
data.getName(); // Example
data.getFirstName(); // Example2
// Get Data
data.get(0).getTitle(); // position 0 : ecaetra
data.get(0).getDescription(); // position 0 : qwerty

Categories