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

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);

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" : {}
}

How To Parse Two JSON Data From Url Simultaneously And Get Url From First JSON And Use That For Getting Data In Second JSON?

I Have A Project And In That Project, I Should Parse Two JSON Together.
I Should Get Url From First JSON Using com.squareup.okhttp3:okhttp:4.4.0 And First JSON Is Looks Like:
{
"Url": {
"Url":"https://example.com/Myjson.json"
}
}
And I Want to Get The "Url" Key From First JSON And Put That Url For Second JSON Url And Second One Is Looks Like:
{
"Head":
{
"Version" : "",
"WebSite" : "",
"Instagram" : "",
"Telegram" : "",
},
"Banner" :
{
"Banner_Tittle":"",
"Banner_Description":""
},
"Version_Banner":
{
"Version_Banner_Tittle" : "",
"Version_Banner_Description" : "",
"Version_Banner_Link" : ""
},
"News": [
{
"Tittle" : "",
"Description" : "",
"Image" : "",
}
],
"Class": [
{
"Tittle" : "",
"Description" : "",
"Image" : "",
}
]
}
And My JSON Parser Class Is Below:
private class GetVersion extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(final Void... arg0) {
JSONObject JsonMain = null;
HttpHandler Handler = new HttpHandler();
String jsonStr = Handler.makeServiceCall("MyFirstJSONURL");
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JsonMain = jsonObj.getJSONObject("Url");
URL_2 = JsonMain.getString("Url");
}
}
}
}
And Now I Want TO Know How To Do That With Android Studio
Declare two classes which extend AsyncTask(one of which you have already declared).
After that, in the onPostExecute method of the first one(GetVersion), execute the second class which takes the URL string and opens a connection to retrieve the JSON file and parse it there.
Something like :-
private class GetLocation......
{
#Override
protected void onPostCreate (Void v)
{
//Execute second class here
}
}

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");
}

Hiding unnecessary stuff of JSONOject in swagger

#XmlElement(name = "dummyAttrib")
#ApiModelProperty(value = "dummyAttrib")
JSONObject dummyAttrib = new JSONObject();
//setter and getter
Now., When I am accessing My Application in Swagger the dummy attribute looks like
"dummyAttrib": {
"values": "java.util.Collection<V>",
"empty": false,
"size": 0,
"entrySet": "Set[java.util.Map.java.util.Map$Entry<K, V>]",
"keySet": [
"K"
]
}
So While entering input for the dummyAttrib, it is bit difficult to delete the entire default stuff and add our own stuff.
Can any one please suggest me to hide the default data given by Swagger?
I want something like
"dummyAttrib":{}
So that I can add my stuff.
In your annotation, you can choose the dataType that you want to map to. So for example:
#XmlElement(name = "dummyAttrib")
#ApiModelProperty(value = "dummyAttrib", dataType = "java.lang.Object)
JSONObject dummyAttrib = new JSONObject();
Which will look like this:
{
"MyModel" : {
"type" : "object",
"properties" : {
"dummyAttrib" : {
"type" : "object",
"description" : "dummyAttrib"
}
}
}
}

Parse Gson with Java to get values

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

Categories