JSON object from java ObjectName.toString - java

I have a java object witch generates this output when i type objectName.toString() :
Bus [id=1, nextStationID=0, previousStationID=0]
Is there a JSON parser that lets me make a JSON from the string that my object generates?
something like: JsonObject x = new JsonObject(busObject.toString())
It is important for me to generate it from the string that i get when calling the .toString method.
Any help is appreciated.

A JSON parser's goal is to make a JSON string from an Object or to create an Object from a JSON string.
In your own answer, manually making a JSON string from your Object is ok but I think that using a JSON parser will make your code easiest to maintain and more efficient.
You can use this toString() method :
public String toString() {
Gson gson = new Gson();
return gson.toJson(this, Bus.class);
}
With this solution, even if you remove or add fields in your class, the toString() method still be ok.
To finish, if you want to convert your object to a JSONObject, I advise you to create a method like toJSONObject and to manually make the conversion inside it.

I have fixed my problem by overriding my toString() and printing directly a json object
StringBuilder builder = new StringBuilder();
builder.append("{\"id\" :");
builder.append(id);
builder.append(", \"latitude\" :");
builder.append(latitude);
builder.append(", \"longitude\" :");
builder.append(longitude);
builder.append("}");
return builder.toString();

i know that this is old, but it is available to create you own json format in toString method. (Eclipse)
Step 1. Right click in edit and go to Source (Alt+Shift+S) -> And click 'Generate toString...'
Step 2. Click edit (as shown in picture)
Edit to String method
Step 3. Create new Template
Step 4. Paste this line: ${object.className}":{"${member.name()}":"${member.value}", "${otherMembers}"}
Step 5. Click ok and apply changes.
Hope this helps anybody. So this way is simpler and faster, you do not have to use gson or any other json parser.

Related

Java, map a json

Here's what I wanna do
I have a json, like:
{
"demoNumber":123,
"demoText":"asdasdasd"
}
and I wanna make a simple String array from it, which should be
["demoNumber","demoText"]
In the app we're making the user can add any type of data, so we can't do data models for everything, that's not an option
I have added json to my Gradle:
dependencies {
implementation 'org.json:json:20180130'
}
But it still can't find the method.
Assuming you have the JSON as a string, this example uses the JSON-java library:
JSONObject jo = new JSONObject(myJsonStr);
Set<String> keys = jo.toMap().keySet();
// You should be able to extract an array from the set of keys
See also https://www.baeldung.com/java-org-json

How to parse a jsonObject or Array in Java

I have an API request from my CRM that can either return a jsonObject if there is only one result, or a jsonArray if there are multiple results. Here are what they look like in JSON Viewer
JsonObject:
JsonArray:
Before you answer, this is not my design, it's my CRM's design, I don't have any control over it, and yes, I don't like how it is designed either. The only reason I am not storing the records in my own database and just parsing that, which would be MUCH easier, is because my account is having issues not running some workflows that would allow me to auto add the records. Is there any way to figure out if the result is an object or an array using java? This is for an android app by the way, I need it to display the records on the phone.
You should use OPT command instead of GET
JSONObject potentialObject=response.getJsonObject("resuslt")
.getJsonObject("Potentials");
// here use opt. if the object is null, it means its not the type you specified
JSONObject row=potentialObject.optJsonObject("row");
if(row==null){
// row is json array .
JSONArray rowArray=potentialObject.getJsonArray("row");
// do whatever you like with rowArray
} else {
// row is json object. do whatever you like with it
}
ONE
You can use instanceof keyword to check the instances as in
if(json instanceof JSONObject){
System.out.println("object");
}else
System.out.println("array");
TWO
BUT I think a better way to do this is choose to use only JSONArray so that the format of your results can be predicated and catered for. JSONArrays can contain JSONObjects. That is they can cover the scope of JSONObject.
For example when you get the response (either in a JSONObject or a JSONArray), you need to store that in an instance. What instance are you going to store it in? So to avoid issues use JSONArray to store the response and provide statements to handle that.
THREE
Also you can try method overloading in java or Generics
Simplest way is to use Moshi, so that you dont have to parse, even in the case of the Model changing later, you have to change your pojo and it will work.
Here is the snippet from readme
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
https://github.com/square/moshi/blob/master/README.md

javax.json produces uncomprehensible json

I have a Java class with two atrributes that I convert to json using this method. I followed this other answer:
Return JSONArray instead of JSONObject, Jersey JAX-RS
public String toString(){
// takes advantage of toString() implementation to format {"a":"b"}
JsonObject json = Json.createObjectBuilder()
.add("sentence", sentence)
.add( "category", category).build();
return json.toString();
}
The String I get is encapsulated into an ArrayList of strings, and sent via HTTP (I am using Jersey):
return Response.status(200).entity(response).build();
How ever, the node client is use cannot parse it properly: it gets the array part, accesses the elements perfectly. But not the json keys and values;
returns undefined:
jsonRespuesta = JSON.parse(body)[0];
console.log(jsonRespuesta);
console.log("Frase: " +jsonRespuesta.sentence + " ,Categoria: " + jsonRespuesta.category);
Returns:
{"sentence":"hola","category":"2"}
Frase: undefined ,Categoria: undefined
What's failing? If it helps, capturing the packets with wireshark displays the array members as strings
Is your java client encoding the JSON twice? I noticed you are adding json strings to an ArrayList, but you should really be adding objects to the ArrayList and then stringifying the whole thing once.
Try using JSON.parse() again on jsonRepuesta and see if that gets you what you're looking for. Alternatively, log out a typeof jsonRepuesta -- looks like it's still a string.
Also, see here.

Converting JSONObject to JSON using GSON

I am having an Java Object which consist many type of variables including a JSONObject.
Whan i debug my object i got the following String for JSONObject:-
{"INCLUSIONS":{"OPTIONS":[{"display":"Complimentary stay for children under 5 without extra bed"}]}}
But when i used:-gson.toJson(JSONObj),I got following
{"myHashMap":{"INCLUSIONS":{"myHashMap":{"OPTIONS":{"myArrayList":[{"myHashMap":{"display":"Complimentary stay for children under 5 without extra bed"}}]}}}}}
Someone please can elaborate why it is converting JSONObject to Map & list ??
Or Any work Around ??
Thanks.
Just use myJsonObj.toString() instead of myJsonObj.toJSON()
Your problem happens because a JSONObject is stored as a HashMap to allow the programmer to reach values with methods based on keys. As example,
String jsonStr = "{'key': 'value'}";
JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
String value = json.get("key").getAsString();
You can figure that json attributes are stored as a HashMap<JsonElement>

How to parse a BasicDBObject into other object

I'm developing a Java application using MongoDB and Java-driver.
I need to parse a BasicDBObject into an own object of my code, and I don't know if there is a way to develop automatically.
Is it possible to parse from BasicDBObject to JSON String? Then, I could parse from JSON String to my own Object, for example with GSON library. Something like
BasicDBObject object;
String myJSONString = object.toString();
Gson gson = new Gson();
MyOwnObject myObject = gson.fromJson(myJSONString, MyOwnObject.class);
And I don't want to add complex to my code, also I don't to add more extern libraries. I don't want to add Gson library or other.
Any ideas?? Is it possible to do this without external libraries??
Thanks!!
You could have taken a look at the API: Just call object#toString() (http://api.mongodb.org/java/2.0/com/mongodb/BasicDBObject.html#toString()).
You could either use Groovy with gmongo library for that, there you have lots of handy tools for such casting.
If the language change is not an option for you, write your own reflection-based mapper. If you POJO is simple enough, the mapper shall be pretty simple.
This is the correct answer to my question
From http://docs.mongodb.org/ecosystem/tutorial/use-java-dbobject-to-perform-saves/
For example, suppose one had a class called Tweet that they wanted to save:
public class Tweet implements DBObject {
/* ... */
}
Then you can say:
Tweet myTweet = new Tweet();
myTweet.put("user", userId);
myTweet.put("message", msg);
myTweet.put("date", new Date());
collection.insert(myTweet);
When a document is retrieved from the database, it is automatically converted to a DBObject. To convert it to an instance of your class, use DBCollection.setObjectClass():
collection.setObjectClass(Tweet.class);
Tweet myTweet = (Tweet)collection.findOne();
If for some reason you wanted to change the message you can simply take that tweet and save it back after updating the field.
Tweet myTweet = (Tweet)collection.findOne();
myTweet.put("message", newMsg);
collection.save(myTweet);

Categories

Resources