I'm a beginner in programming, and I need some help. Is it possible to convert an HTTP (that returns a Json) automatic call to object in java? For example it reads the request, and when I call System.out.println (obj) it already returns me an OBJECT of this request, instead of String. Is it possible? If so, could you help me ... I already did the method to call the url and return string, but I need to return OBJECT, so I can compare with HashCode and Equals.
My code:
enter image description here
output:
{"header":{"messageId":"02938ec7-b2c3-4131-8ecf-3ad3a8509b41"},"body":{"products"
What I wanted: output
Informacoes [header=Header [messageId=66d22c00-bddc-4ea7-afbd-7c7225fcb914], body=Body
From what I can understand from your question, it looks like Gson might be useful. Gson is a library that allows you to convert between JSON and Java primitives/objects. Here's an example I just wrote:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
}
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{\"value1\":1,\"value2\":\"abc\"}";
BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class);
}
This code converts the json {"value1":1,"value2":"abc"} into an object of the class BagOfPrimitives.
To add Gson to your project, go here, click "Downloads" at the top right, and click "jar". Then follow these instructions to add the jar file to your project. Then you should be able to write import com.google.gson.* at the top of your class and use Gson in your java code.
Related
I need to convert a json string to particular type based on the function's return type. The json string could also be a plain string. I am facing issues while converting the strings using gson.fromJson method.
Why is an exception thrown in gson.fromJson if the string contains a space? And how do I get around this?
import java.lang.reflect.Method;
import com.google.gson.Gson;
class Trial {
Object retu() {
return "BEVERLY OUTLAW";
}
}
public class sample {
public static void main (String args[]) {
Gson gson = new Gson();
Trial obj = new Trial();
Method func = obj.getClass().getDeclaredMethods()[0];
Object o = gson.fromJson("beverlyoutlaw", func.getGenericReturnType());
System.out.println(o); ---> this prints beverlyoutlaw
o = gson.fromJson("beverly outlaw", func.getGenericReturnType()); ---> This throws an exception!
System.out.println(o);
}
}
Strings in Json need to be surrounden by quotes. That is - in the Json itself!
Neither "beverlyoutlaw" nor "beverly outlaw" contain quotes in the string - the quotes are just part of the Java String literal.
Apparently Gson does not enforce this for strings without spaces - for strings with spaces however it is strictly necessary.
To fix your issue, use o = gson.fromJson("\"beverly outlaw\"", func.getGenericReturnType());
My json:
{"code":200,"data":[{"xxx":"xxx","yyy":1234,"zzz":"56789"},{...}]}
I need Gson to take the data part in the shape of [{...}] and put it to simple String. But Gson keeps trying to parse it as an array and throws this JsonSyntaxException. Is it possible to get the result as I want it?
Gson fromJson call:
ParsedResponse parsedResponse = gson.fromJson(jsonString, ParsedResponse.class);
ParsedResponse class:
public class ParsedResponse {
#SerializedName("code")
private int code;
#SerializedName("data")
private String data;
private int statusCode;
// getters, setters
}
EDIT:
The system works when I have {...} in data, so why couldn't it work with [{...}]? I just need Gson to take the string [{...}] and put it to String variable.
Basically, no. Just put into Array and then convert to what you need.
Other approach is to see if you can over-ride some parser implementation of GSON.
Or write your own JSON to reflection library. :-).
*** Or, just write your own JSON parsing as your data format might be well-known to you and simply enough. :-)
My company has a webserver API that provides search results in JSON format. I'm responsible for developing an Android app that consumes that API, and I have made some classes that model the objects in the JSON responses.
For the sake of habit and my own preference, I use to write my code in English only. However, most of the JSON keys are not in English. This way, I cannot readily use GSON to convert the JSON strings into Java Objects -- at least that is what I think.
I was wondering if there is any way to reference just once per class the connection between the JSON key and their corresponding instance variables in the code. In a way that after referenced, I could simply instantiate objects from JSON and create JSON strings from objects.
Is that possible?
Example:
// Java code
class Model {
String name;
Integer age;
}
// JSON with keys in Portuguese
{
"nome" : "Mark M.", # Key "nome" matches variable "name"
"idade" : 30 # Key "idade" matches variable "age"
}
Use the #SerializedName annotation.
Here is an example of how this annotation is meant to be used:
public class SomeClassWithFields {
#SerializedName("name") private final String someField;
private final String someOtherField;
public SomeClassWithFields(String a, String b) {
this.someField = a;
this.someOtherField = b;
}
}
The following shows the output that is generated when serializing an instance of the above example class:
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(objectToSerialize);
System.out.println(jsonRepresentation);
===== OUTPUT =====
{"name":"a","someOtherField":"b"}
Source: SerializedName Javadocs
I cannot find any documentation on this, but it seems Gson serializes fields of sub-class before those of the super-class:
class G9 {
static class B { String s1 = "1"; String s2 = "2"; }
static class C extends B { String s3 = "3"; }
public static void main(String args[]) {
System.out.println(new Gson().toJson(new C()));
}
}
This program produces the following output:
/cygdrive/c/Java/jdk1.8.0/bin/javac -classpath gson-2.1.jar -g G9.java && /cygdrive/c/Java/jdk1.8.0/bin/java -classpath ".;gson-2.1.jar" G9
{"s3":"3","s1":"1","s2":"2"}
I would like it to be the following:
{"s1":"1","s2":"2","s3":"3"}
I realize I can do this with a TypeAdapter but that essentially amounts to
implementing serialization
figuring out how to delegate deserialization to Gson OR implementing that as well.
Is there an easier way to achieve this? I guess I am looking for a new FieldOrderingTypeAdapter<C>(C.class, "s1", "s2", "s3") or GsonBuilder.setFieldOrder("s1", "s2", "s3") or something.
I am using Gson 2.1.
From JSON order mixed up:
You cannot and should not rely on the ordering of elements within a
JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of
the elements as they see fit. This is not a bug.
As far as I know, there is no simple way to get around this.
Is their an easy way or library to convert a JSON String to a Java object such that I can easily reference the elements in a JSP page? I think Map's can be referenced with simple dot notation in JSP pages, so JSON -> Map object should work?
UPDATE: Thank you for all the JSON Java libraries. In particular, I'm looking for a library that makes it easy for consumption in JSP pages. That means either the Java object created has appropriate getter methods corresponding to names of JSON nodes (is this possible?) or there's some other mechanism which makes it easy like the Map object.
Use Jackson.
Updated:
If you have an arbitrary json string Jackson can return a map object to access the properties values.
Here a simple example.
#Test
public void testJsonMap() throws JsonParseException, JsonMappingException, IOException {
String json = "{\"number\":\"8119123912\",\"msg\":\"Hello world\"}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
System.out.println("number:" + map.get("number") + " msg:" + map.get("msg"));
}
Output:
number:8119123912 msg:Hello world
Try GSON, here is a tutorial.
This library should do what you want: http://www.json.org/java/
DWR can be used for this purpose DWR - Easy Ajax for JAVA .
Lets consider this java class.
class Employee
{
int id;
String eName;
// setters and getters
}
In javascript JSON object
var employee = {
id : null,
name : null
};
This is the call to java method from javascript function.
EmployeeUtil.getRow(employee,dwrData);
In getRow() of EmployeeUtil class, return type of method will be Employee.
Employee getRow();
So using the setters of Employee set the data.
dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned which is Employee bean will be in callback function.
Just initialize this in javascript JSON object.
Now the JSON object can be parsed and displayed in jsp.
This example shows Dynamically Editing a Table
Hope this helps ....