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

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

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
}
}

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

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