I'm trying to create a JSON Object from a String. The String looks like this: {"case":"getAllProducts"}.
Why is jobj always empty?
String received = textMessage.getText();
System.out.println(received); //{"case":"getAllProducts"} - perfect
JsonObject jobj = new Gson().fromJson(received, JsonObject.class);
System.out.println(jobj); //{} - why empty???
String reqCase = jobj.get("case").getAsString();
I already checked out other articles here where its done exactly like I did. I can't find my problem here..
Instead of
new Gson().fromJson(received, JsonObject.class);
it should be
new Gson().fromJson(received, YourClass.class);
where YourClass is a user defined class having attributes same as the attributes in your JSON.
Related
After some researchs, I didn't have found any solutions to this problem:
when I create a JSONObject (org.json) from a file, it return "empty":false. Why does it return this and how can I fix it?
Java:
JSONObject config = new JSONObject(Files.readAllLines(Paths.get("config/maj.json")));
JSON:
{"FyloZ":"0"}
Files.readAllLines is working return the right value.
Thanks!
Files.readAllLines() returns List<String>, not a String.
So actually you are using the following constructor (accepting a single Object parameter):
https://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.Object-
Construct a JSONObject from an Object using bean getters
The only getter-style method of a List is isEmpty(), so you get that 'empty: false' thing.
Try the following:
String json = new String(Files.readAllBytes(Paths.get("config/maj.json")), "utf-8");
JSONObject config = new JSONObject(json);
Here we read JSON as bytes, convert them to a string (assuming it's in utf-8) and then create a JSONObject from it.
I have an object which can be serialized to JSON using Jackson. I want to add this object to a JSONObject and have the content serialized
JSONObject msg = new JSONObject();
put("something", "value");
put("myThing", myThing);
mapper.writeValueAsString(msg);
String s = msg.toString();
but the result is
{"something":"value","myThing":"com.example.things"}
I have tried
put("myThing", mapper.valueToTree(myThing))
// and
put("myThing", mapper.writeValueAsString(myThing))
however both of these result in the child object beening escaped
{"something":"value","myThing":"{\"foo\":\"bar\"}"}
How do I get what I really want ...
{"something":"value","myThing":{"foo":"bar"}}
Create an JSONObject for the myThing object.
Like this:
JSONObject obj = new JSONObject();
obj.put("foo", myThing.getFoo());
and add this to the main JSONObject:
JSONObject msg = new JSONObject();
msg.put("something", "value");
msg.put("myThing", obj);
Another method is to use Annotations to mark the fields in a class which should be serialized and then generate the JSON Object via reflection.
I have some classes on Github which you can use.
Example for usage:
public class MyClass {
#JSONElement(name = "foo")
private String field1;
MyClass(String f) {
this.field1 = f;
}
[...]
}
MyClass object = new MyClass("bar");
JSONObject json = JSONMarshaller.marshall(object);
The resulting JSON for this object is:
{"foo":"bar"}
I had managed to mix up org.json and com.fasterxml.jackson.
ObjectNode msg = mapper.createObjectNode();
msg.put("something", "value");
msg.put("myThing", mapper.valueToTree(myThing));
String s = msg.toString();
This now gives the output I was expecting
Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.
I have a String in java that might look like this:
String str = "Hello this is #David's first comment #excited"
I want to convert this string to a json object, but it throws an error when I use the below:
JSONObject json = new JSONObject(str);
I have found out that it throws an error due to the '#' symbol.
Is there any other way to convert the string to json, without much hassle ?
The problem is not so much the '#' symbols; it's that you are trying to parse the string as if it's already JSON. You probably want something like this:
JSONObject json = new JSONObject();
json.put("firstString", str);
String jsonString = json.toString();
or, more briefly (if all you want is a quoted JSON string:
String jsonString = JSONObject.valueToString(str);
I have some code not shown here that pulls an IMEI number in JSON format from a database via a WCF and I now have it in the following format which I can display,
{"getIMEIResult":"268003456767887"}
Via,
jsonResponse = new JSONObject(new String(buffer));
IMEICheckResponse = jsonResponse.toString();
And then Toast IMEICheckResponse to get
{"getIMEIResult":"268003456767887"}.
How do I extract 268003456767887 from the JSON object and put it into the IMEICheckResponse string?
Cheers,
Mike.
Its very simple,
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
Log.d("output", IMEICheckResponse);