I'm having following class
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public Result OperationResult;
public String Messages;
public String UpdateAvailable;
public Object ResultData;
}
I'm having json string like,
{"OperationResult":0,"Messages":"","UpdateAvailable":"","ResultData":{"SessionId":"3b44a524-fc2a-499b-a16e-6d96339a6b5b","UserName":"admin","AccoundId":null,"Roles":["Administrator"],"DisplayName":"Admin","Status":3,"Type":1}}
I want to assign this json string to above class.I'm using GSON for assign json string to java object.In normal class i can assign json string to java object. But for this class i couldn't assign directly. Please any one help me,
Now i'm assigning like,
String formatedjsonstring = {json string};
Log.i("FORMAT STRING:",formatedjsonstring);
Gson gson = new Gson();
ReturnData returndata = (ReturnData) gson.fromJson(
formatedjsonstring, ReturnData.class);
You could use JavaJson from sourceforge. You could pass your json string to JsonObject .parse().
Try this
JsonObject json = JsonObject .parse("{\"OperationResult\":0, \"Messages\":\"UpdateAvailable\"");
System.out.println("OperationResult=" + json.get("OperationResult"));
System.out.println("Messages=" + json.get("Messages"));
https://sourceforge.net/projects/javajson/
Since your Java class doesn't resemble your JSON in any way, shape or form ... you're going to have a problem with that.
Problem #1: OperationResult should be an int
Problem #2: You're declared ResultData as an Object ... Java doesn't work like that.
You need your POJO to match the JSON:
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public int OperationResult;
public String Messages;
public String UpdateAvailable;
public MyResultData ResultData;
}
class MyResultData {
public String SessionId;
public String UserName;
public String AccountId;
public List<String> Roles;
public String DisplayName;
public int Status;
public int Type;
}
ReturnData rd = new Gson().fromJson(jsonString, ReturnData.class);
I'd also consider using Gson's #SerializedName("name") annotation to convert the PascalCase field names in your JSON to camelCase field names in Java.
#SerializedName("OperationResult") public int operationResult;
Try this:
java.lang.reflect.Type type = new TypeToken<ReturnData>(){}.getType();
ReturnData rd = new Gson().fromJson(jsonString, type);
Related
I have this as a substring. It is a JSON string. I am trying to get the id string from it. I was able to do this by using two indexOf's and then substring the two indexOf's. What is a better solution.
Here is my string
"{"id":"762c094a-4b65-499e-b5b2-de34ef8d726e","createdTimestamp":1605558195131,"username":"sssdv","enabled":false,"totp":false,"emailVerified":false,"firstName":"cdf","lastName":"dddz","email":"hgddf#fdaddf.com","disableableCredentialTypes":[],"requiredActions":[],"notBefore":0,"access":{"manageGroupMembership":true,"view":true,"mapRoles":true,"impersonate":true,"manage":true}}"
And here is my code.
int id = results.indexOf("id");
int cr = results.indexOf("createdTimestamp");
String strId = results.substring(id + 5, cr - 3);
A better solution is to use an actual JSON parser. There are plenty out there. Take a look at this answer on a different question. I would suggest using Gson:
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
JsonElement element = gson.fromJson(json, JsonElement.class); // Parse it
String id = element.getAsJsonObject().get("id").getAsString(); // Get your desired element
System.out.println(id);
An even better solution would be to create a class with the fields from your JSON and parse the JSON string to that class:
public class MyObject {
// The names and types of these fields must match the ones in your JSON string
private String id, username, firstName, lastName, email;
private long createdTimestamp;
private boolean enabled, totp, emailVerified;
private String[] disableableCredentialTypes, requiredActions;
private int notBefore;
private Access access;
public String getId() {
return id;
}
// Other getters and setters...
private static class Access {
private boolean manageGroupMembership, view, mapRoles, impersonate, manage;
// ...
}
public static void main(String[] args) throws IOException {
String json = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Create the Gson instance
MyObject object = gson.fromJson(json, MyObject.class); // Parse the string to your data type
System.out.println(object.getId()); // Print the id
}
}
String results = "{\"id\":\"762c094a-4b65-499e-b5b2-de34ef8d726e\",\"createdTimestamp\":1605558195131,\"username\":\"sssdv\",\"enabled\":false,\"totp\":false,\"emailVerified\":false,\"firstName\":\"cdf\",\"lastName\":\"dddz\",\"email\":\"hgddf#fdaddf.com\",\"disableableCredentialTypes\":[],\"requiredActions\":[],\"notBefore\":0,\"access\":{\"manageGroupMembership\":true,\"view\":true,\"mapRoles\":true,\"impersonate\":true,\"manage\":true}}";
String[] parts = results.split("\"");
System.out.println(parts[3]); //gives the id, every time
I googled and saw many question and answers but none of it are helping me. Here is the issue. I have a Class
public class ResponseData {
public static transient final int SUCCESS = 1;
public static transient final int FAILED = 0;
public String id;
public int status;
public Object data;
// Constructor, Getters and Setters
}
I'm using ResponseData as the common return object for my server and the server has many APIs. In one of the API, it is setting the data parameter to ArrayList. Then converting as json using Gson (2.8.0).
And then sending back to caller. (It's not HTTP)
public class MyServerClass {
private final Gson gson;
public MyServerClass() {
GsonBuilder builder = new GsonBuilder();
gson = builder.serializeNulls().create();
}
public String someAPI() {
ResponseData responseData = new Response("myid", ResponseData.SUCCESS, Arrays.asList("Some string value", ArrayList<MyCustomObject>, "Some other Value"));
String json = gson.toJson(response)
}
}
And the MyCustomClass is a plain POJO class with some set of attributes.
public class MyCustomClass {
private String name;
private String id;
private String createdTime;
//Constructor, Getters & Setters
}
At the receiving side I have below code.
private Gson gson = null;
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
///
ResponseData response = gson.fromJson(eventData, ResponseData.class);
ArrayList list = (ArrayList) respone.getData();
String val = (String) list.get(0);
List rwData = (List) list.get(1);
for(List<List<String>> entry: rwData) { // Exception is thrown Here. How to get it as List?
//Coverting Data
}
Exception is thrown when trying to get the data as List<List<String>>. How to convert the json string properly here? I cannot use the MyCustomClass at my client layer. That's why trying list
Exception occured:com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.List
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.List
I am calling a webservice which gives me a json like this
{
"discussions": [{
"id": 54,
"name": "Test Discusssion",
"discussion": 41,
"created": 1472816138,
"modified": 1472816138,
"subject": "Test Discusssion",
"message": "<p>Welcome all to test discussion<\/p>",
}],
"warnings": []
}
But in android I am parsing it as
ArrayList<MoodleDiscussion> mDiscussions = gson.fromJson(reader,
new TypeToken<List<MoodleDiscussion>>() {
}.getType());
And the error I am getting is
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
I want to convert the received json into an array how should I ?
Here is the MoodleDiscussion class
public class MoodleDiscussion extends SugarRecord < MoodleDiscussion > {#
SerializedName("id") int discussionid;#
SerializedName("name") String name;#
SerializedName("subject") String subject;
public int getDiscussionid() {
return discussionid;
}
public String getName() {
return name;
}
public int getUserid() {
return userid;
}
public String getSubject() {
return subject;
}
}
The list you're trying to parse is contained within a nested json data structure that also needs to be represented in java classes if Gson is to parse it correctly.
You'll need a container class that looks something like this:
public class MoodleDiscussionResponse {
private List<MoodleDiscussion> discussions;
private List<Object> warnings;
public List<MoodleDiscussion> getDiscussions() {
return discussions;
}
public List<Object> getWarnings() {
return warnings;
}
}
Then you should be able to read it like so:
MoodleDiscussionResponse response = gson.fromJson(reader, MoodleDiscussionResponse.class);
List<MoodleDiscussion> mDiscussions = response.getDiscussions();
Define class the same:
class Discussion implements Serializable
{
#SerializedName("id")
int id;
#SerializedName("name")
String name;
#SerializedName("discussion")
String discussion;
bla bla
}
and:
class ResultResponse implements Serializable
{
#SerializedName("discussions")
List<Discussion> mDiscussion = new ArrayList<>();
}
I think that is enough to parser using gson.
You can not using below code in this case :)
ArrayList<MoodleDiscussion> mDiscussions = gson.fromJson(reader,
new TypeToken<List<MoodleDiscussion>>() {
}.getType());
you can parse in two ways first get array list of json object and loop it
JSONArray discussionsList = obj1.getJSONArray("discussions");
for (int i = 0; i < discussionsList.length(); i++) {
JSONObject jsonObject = orderList.getJSONObject(i);
Type type = new TypeToken<MoodleDiscussion>() {
}.getType();
CompletedOrderData completedOrderData = new Gson().fromJson(jsonObject.toString(), type);
disscussionDataArrayList.add(completedOrderData);
and second way is parse jsonArray object as below
Type type = new TypeToken<ArrayList<MoodleDiscussion>>() {
}.getType();
disscussionDataArrayList=new Gson().fromJson(orderList,type);
I am trying to parse through a JSON string and convert it to the following POJO:
package apicall;
//POJO representation of OAuthAccessToken
public class OAuthAccessToken {
private String tokenType;
private String tokenValue;
public OAuthAccessToken(String tokenType,String tokenValue) {
this.tokenType=tokenType;
this.tokenValue=tokenValue;
}
public String toString() {
return "tokenType="+tokenType+"\ntokenValue="+tokenValue;
}
public String getTokenValue() {
return tokenValue;
}
public String getTokenType() {
return tokenType;
}
}
In order to do this I have written the following code:
Gson gson=new Gson();
String responseJSONString="{\"access_token\" : \"2YotnFZFEjr1zCsicMWpAA\",\"token_type\" : \"bearer\"}";
OAuthAccessToken token=gson.fromJson(responseJSONString, OAuthAccessToken.class);
System.out.println(token);
When I run the code, I get the following output:
tokenType=null
tokenValue=null
Instead of
tokenType=bearer
tokenValue=2YotnFZFEjr1zCsicMWpAA
I don't understand if there's anything I've done wrong. Please help.
You can get the expected result by annotating your fields like:
#SerializedName("token_type")
private final String tokenType;
#SerializedName("access_token")
private final String tokenValue;
How is Gson supposed to know how to populate your object? You don't have a no-arg constructor, and the fields of your object don't match the fields in the JSON object.
Make your object as following:
public class OAuthAccessToken {
private String accessToken;
private String tokenType;
OAuthAccessToken() {
}
...
}
The class should have the exact field name as the json, so if your json have 2 keys: "access_token" and "token_type", the class should have 2 fields:
private String access_token;
private String token_type;
And, of course you need to change the getters/setters accordingly.
Say I have a JSON string like:
{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"200"}, ...
My accessor:
import com.google.gson.annotations.SerializedName;
public class accessorClass {
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("image")
private String image;
// how do I place the sub-arrays for the image here?
...
public final String get_title() {
return this.title;
}
public final String get_url() {
return this.url;
}
public final String get_image() {
return this.image;
}
...
}
And my main:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jstring).getAsJsonArray();
ArrayList<accessorClass > aens = new ArrayList<accessorClass >();
for(JsonElement obj : Jarray )
{
accessorClass ens = gson.fromJson( obj , accessorClass .class);
aens.add(ens);
}
What do you think would be the best way to get those sub-arrays for the image here?
FYI if your JSON is an array: {"results:":[{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}
Then you need a wrapper class:
class WebServiceResult {
public List<AccessorClass> results;
}
If your JSON isn't formatted like that, then your For loop you created will do it, (if not a little clunky, would be better if your JSON is formed like above).
Create an Image class
class ImageClass {
private String url;
private int width;
private int height;
// Getters and setters
}
Then change your AccessorClass
#SerializedName("image")
private ImageClass image;
// Getter and setter
Then GSON the incoming String
Gson gson = new Gson();
AccessorClass object = gson.fromJson(result, AccessorClass.class);
Job done.