Figured out what the problem was. Needed to extract the jsonobject instead of getting the string. Here was the line that fixed the issue:
UserIdentifier userIdentifier = gson.fromJson(jsonResponse.getJSONObject("userIdentifier").toString(), UserIdentifier.class);
Answer from Richard on Stack OverflowFigured out what the problem was. Needed to extract the jsonobject instead of getting the string. Here was the line that fixed the issue:
UserIdentifier userIdentifier = gson.fromJson(jsonResponse.getJSONObject("userIdentifier").toString(), UserIdentifier.class);
You may need use gson
class Name{
String resultCode;
UserIdentifier useridentifier;
//getters
}
Gson gson=new Gson();
Name name=gson.fromJson(jsonString,Name.class);
How to convert a Java Object to JsonObject type of couch base?
Convert Java object to JSON without external library
Converting Json to Java object
How to convert object to json in controller?
Videos
If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.
SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
I feel like an idiot, I mean, I have been programming for a few years, mostly C# and Java, but all the REST apis I made was built with .NET, so I had no need for it.
Well, I can't find how to convert a Java object to a JSON WITHOUT the need of an external library, anyone?
I want to convert the following text file into a java object list, HashMaps seem not complext enough as the text file is Json
info = [{"key":"1",
"request":"ok",
"group": "user"},{...},...{}]