Parse Gson with Java to get values - java

I would like to get value from JSON. I am using Google Gson.
Here is my Json format :
{
"idContact" : 1,
"message" : "myMessage",
"date" : "07/03/2016 21:58:38",
"Client" : {
"idClient" : 122,
"lastName" : "LASTNAME",
"firstName" : "FIRSTNAME",
"phone" : "060000"
}
}
I can get values from message and date by using :
Gson gson = new GsonBuilder().create();
MyClass myClass = gson.fromJson(jsonMessage, MyClass.class);
System.out.println("message: "+smsJson.getMessage());
But I can't have values for my Client. When I do System.out.println("message: "+smsJson.getClient().getId()); I have null pointer exception.
MyClass is :
public class MyClass {
String message;
String date;
Contact contact;
Client client;
}
Thanks

Related

Java PUT Request Zotero 400 Bad Request

I am trying to send PUT request to the Zotero API, but I keep getting an error:
Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: ['itemType' property not provided]
The JSON being sent is fine, so it is something with my code.
private void handleUpdateItemButton(ActionEvent event) throws IOException {
Properties props = restConnection.getAccessProperties();
ResponseEntity<JsonNode> res = restConnection.getRestTemplate().exchange(this.getItem(props, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
if (res.getStatusCode() == HttpStatus.OK) {
JsonNode jsonNode = res.getBody();
printJSON(jsonNode);
JSONObject jsonObject = convertNodetoObject(jsonNode);
JSONObject jsonData = jsonObject.getJSONObject("data");
//jsonObject.getJSONObject("data").put("title", "This is the new title");
jsonData.put("title", "This is the new title");
ResponseEntity<JsonNode> updatedItem = restConnection.getRestTemplate().exchange(this.updateItem(props, jsonData, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
}
else{
System.out.println("This item cannot be updated");
}
}
The method above then calls the method below
private RequestEntity updateItem(Properties props, JSONObject item, String itemKey) throws JsonProcessingException {
ResponseEntity<JsonNode> res = restConnection.getRestTemplate().exchange(this.getItem(props, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
return RequestEntity
.put(restConnection.getZoteroBaseURL() + "/users/" + props.getProperty("username") + "/items/" + itemKey)
.header("Zotero-API-Version", "3")
.header("Zotero-API-Key", props.getProperty("key"))
.header("If-Unmodified-Since-Version", numberBody.get("version").toString())
.header("Content-Type", "application/json")
.body(item);
}
Not really sure what is wrong. I'd appreciate any help - zoter-dev said that the PUT request should work and it's something with my code. Thanks!
I'd suggest you take a good look at the Zotero Web API documentation.
If you examine the creating an item section you'll find what you need to pass in your API call in order for it to work:
[
{
"itemType" : "book",
"title" : "My Book",
"creators" : [
{
"creatorType":"author",
"firstName" : "Sam",
"lastName" : "McAuthor"
},
{
"creatorType":"editor",
"name" : "John T. Singlefield"
}
],
"tags" : [
{ "tag" : "awesome" },
{ "tag" : "rad", "type" : 1 }
],
"collections" : [
"BCDE3456", "CDEF4567"
],
"relations" : {
"owl:sameAs" : "http://zotero.org/groups/1/items/JKLM6543",
"dc:relation" : "http://zotero.org/groups/1/items/PQRS6789",
"dc:replaces" : "http://zotero.org/users/1/items/BCDE5432"
}
}
]
It's stated that All properties other than itemType, tags, collections, and relations are optional, meaning itemType is mandatory.
You must fill in these four properties, at least, if you want your call to succeed.
If you don't have any data for tags, collections or relations you could just pass empty property values:
{
"itemType" : "note",
"note" : "My sample note",
"tags" : [],
"collections" : [],
"relations" : {}
}

Handles json objects without knowing the attribute name and number of attributes

I tried to process the request with the example below:
"type" : "NEWS",
"content" : {
"title" : "Test Message",
"message" : "This is a message",
"buttonCaption" : "Click me"
}
Or maybe:
"type" : "NEWS",
"content" : {
"title" : "Test Message",
"message" : "This is a message",
"buttonCaption" : "Click me",
"anotherField" : "values"
}
Sometime maybe:
"type" : "NEWS",
"content" : {
"name" : "Test Message",
"anotherProperties" : "This is a message",
"ohMyGodAnotherFields" : "Click me"
}
So I cannot create a particular Object.
How can I handle it in Spring controller?
You can use JsonNode in your resource class like:
public class Foo {
private String type;
private JsonNode content;
// ...
}
And accept it as #RequestBody in your controller:
#PostMapping
public ResponseEntity<Foo> foo(#RequestBody Foo foo){
// do something with your foo...
}
You can read more aboot JsonNode here.
You have to get the keys, using java.util.Iterator.
JSONObject jsonObj = new JSONObject(JSONString);
Iterator keys = jsonObj.keys();
while (keys.hasNext()) {
String keyStr = keys.next().toString();
String value = jsonObj.getStrin(keyStr);
}
or You can try this:
JSONObject jsonObj = new JSONObject(JSONString);
if (jsonObj.has("key")) {
String value = jsonObj.getString("key");
}

How to Read JSON data from txt file in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I am now want to read a series of JSON data(Nodes data) from local txt file(shown below, NODES.txt ). I use javax.json to do this.
Currently, I have a Node class which contains the attributes:type, id, geometry class(contains type, coordinates), properties class (contains name);
Here is the data I need to retrieve, it contains more than 500 nodes in it, here I just list 3 of them, so I need to use a loop to do it, I am quite new to this, please help !!
The sample JSON data in NODES.txt
[
{
"type" : "Feature",
"id" : 8005583,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.2288,
48.7578
]
},
"properties" : {
"name" : 1
}
},
{
"type" : "Feature",
"id" : 8005612,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.2271,
48.7471
]
},
"properties" : {
"name" : 2
}
},
{
"type" : "Feature",
"id" : 8004171,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.266,
48.7563
]
},
"properties" : {
"name" : 3
}
},
****A Lot In the Between****
{
"type" : "Feature",
"id" : 8004172,
"geometry" : {
"type" : "Point",
"coordinates" : [
-113.226,
45.7563
]
},
"properties" : {
"name" : 526
}
}
]
First, read in the file and store the content in ONE String:
BufferedReader reader = new BufferedReader(new FileReader("NODES.txt"));
String json = "";
try {
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = reader.readLine();
}
json = sb.toString();
} finally {
reader.close();
}
Then parse the Json data from the String:
JSONObject object = new JSONObject(json); // this will get you the entire JSON node
JSONArray array = object.getJSONArray("Node"); // put in whatever your JSON data name here, this will get you an array of all the nodes
ArrayList<Node> nodeList = new ArrayList(array.length())<Node>;
for(int i=0; i<array.length(); i++){ // loop through the nodes
JSONObject temp = array.getJSONObject(i);
nodeList.get(i).setType(temp.getString("type")); //start setting the values for your node...
....
....
}
Create classes to represent the entries:
Feature.java:
import java.util.Map;
public class Node {
public String type;
public String id;
public Geometry geometry;
public Properties properties;
}
Geometry.java:
import java.util.List;
public class Geometry {
public String type;
public List<Double> coordinates;
}
Properties.java:
public class Properties {
public String name;
}
And an application main class to drive the processing.
Main.java:
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.Reader;
public class Main {
public static void main(String[] args) throws Exception {
try (Reader reader = new FileReader("NODES.txt")) {
Gson gson = new Gson();
Node[] features = gson.fromJson(reader, Node[].class);
// work with features
}
}
}

GSON - JsonSyntaxException - Expected name at line 7 column 4

I have the following result class whose object is to be returned as JSON.
public class Result {
public String objectid;
public String dtype;
public String type;
public String name;
public String description;
public Result() {
this.objectid = "";
this.dtype= "";
this.type="";
this.name= "";
this.description = "";
}
public String getObjectid() {
return objectid;
}
public void setObjectid(String s) {
this.objectid = s;
}
public String getDtype() {
return dtype;
}
public void setDtype(String s) {
this.dtype= s;
}
public String getType() {
return type;
}
public void setType(String s) {
this.type = s;
}
public String getName() {
return name;
}
public void setName(String s) {
this.name = s;
}
public String getDescription() {
return description;
}
public void setDescription(String s) {
this.description = s;
}
}
I have a configuration json which is read my the main .java and returned as json as HTTP RESPONSE. It is as below:
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test" // removed
},
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}
Main .java
Using Gson, it reads the configuration.json file and has to return a json.
My code:
Gson g = new Gson();
Result r = g.fromJson(res.toString(), Result.class);
where res.toString() gets me the configuration.json file content as string.
My problem:
I am experiencing the following exception:
Exception com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3
Any pointers?
If this is the actual json: You have an extra comma here and a spelling error. The error says you have bad json syntax. So this is probably one of the first places to look.
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name " : "test",
"description" : "test", //delete this comma
},
{
"objectid" : "test",
"dtyoe" : "test", // spelling error
"type" : "test",
"name " : "test",
"description" : "test"
}
You also seem to be parsing two objects and telling gson you want one result object from it.
Consider either parsing the objects separately or tell gson you want a result array Back
use
catch(JsonSyntaxException e)
instead of
catch(MalformedJsonException e)
because MalformedJsonException is some internal exception while JsonSyntaxException is the one that actually get thrown. here is a code snippet
String response="Something";
JsonElement my_json;
try {
my_json=jsonParser.parse(response);
} catch(JsonSyntaxException e) {
e.printStackTrace();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
my_json=jsonParser.parse(reader);
}
You have two objects but getting one object from GSON. either you should use below format of JSON string to get Result object from this JSON string.
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}
Second option :-
You will have to change JSON string format. you will have to change it in JSON array and get ArrayList of this object, After that, we can get Result object using array list index.new JSON string would be like this.
{"resultArray":[{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
},
{
"objectid" : "test",
"dtype" : "test",
"type" : "test",
"name" : "test",
"description" : "test"
}]}
And java code to fetch Result Object.
Gson g = new Gson();
ResultList r = g.fromJson(res.toString(), ResultList.class);
ArrayList<Result> resultList = r.getResultList();
for(int x=0 ;x<resultList.size();x++){
Result result = resultList.get(x);
}
ResultList Model is:-
public class ResultList {
#SerializedName("resultArray")
public ArrayList<Result> resultList;
public getResultList(){
return resultList;
}
}
#Note: - Result.java would be used same as given above.
My Issue was the JSON string was too long for the parser to handle. I shortened the string and it worked.

How To Parse(DeSerialise) Json String in java using Gson Library

I need to parse the following JSON in Java using Gson Library. Can anyone help me as I am new to JSON?
alarmEvent = {
"version" : "1.0"
"type" : "ALARM",
"nodeId" : "",
"timeStamp" : "",
"params" : {
"paramId" : "",
"alarmType" : "",
"category" : "",
"source" : "",
"parameter": "",
"alarm" : "",
"alias" : "",
"duration" : ""
}
}
You can create an AlarmEvent class, containing a member for each field you expect to see in the JSON object. For example:
class AlarmEvent {
private String version;
private String type;
....
}
Then, you can instantiate an object of this type as follows:
AlarmEvent a = new Gson().fromJson(json, AlarmEvent.class);
You can now access the fields directly as a.version, a.type, etc.
JsonObject jobj = new Gson().fromJson(json, JsonObject.class);

Categories