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
Related
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 using Jackson library with java 11 so basically I am able to read the below JSON into a string format
{
"schemas":[
"urn:params:core:2.0:User",
"urn:params:core:3.0:User"
],
},
}
here below is the set in which I have to fill the values of schemas from above json
private Set<String> setschemas = null;
right now I am able to read the above json into a string named finaljson , now please advise how can I read the differnt value of schemas from above json string named finaljson and set it to set named setschemas
if (node.has("schemas")) {
// *** here I want to read the differernt value of schemas and set it to a set
// named setschemas
// *****
}
you can create the following classes that represent the json structure
class MyJsonObject {
private AppIdentity appIdentity;
private Set<String> schemas;
private String userName;
}
class AppIdentity {
private String clientId;
private String username;
}
than you can use
final MyJsonObject myJsonObject = new ObjectMapper().readValue(finaljson, MyJsonObject.class); to read the json to JAVA object
so it can manipulated like myJsonObject.schemas.size() > 0 and such...
there are a lot of examples in the internet
*keep in mind, this solution only works when the json structure and fields name are known in advanced
With your approach, this would be simplest one:
if(node.has("schemas")) {
JsonNode schemaNode = node.get("schemas");
Set<String> schemaSet = objectMapper.convertValue(schemaNode, Set.class);
System.out.println("schemaSet" + schemaSet);
}
There are various ways to deal with JSON one is described here
1) You can create a class of JSON structure as follows with help online JSON to POJO convertor (Note:: Add Setters and Getters with help of IDE)
class AppJson {
private Set<AppIdentity> appIdentity;
private Set<String> schemas;
private String userName;
private Manager ManagerObject;
private String division;
private String organization;
private String costCenter;
private String employeeNumber;
}
class AppIdentity {
private String clientId;
private String username;
}
class Manager {
private String value;
private String $ref;
private String displayName;
private String $Ref;
}
2) Use above for object conversion.
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"appIdentity\":[{\"clientId\":\"9a41763c642\",\"username\":\"XXX\"}],\"schemas\":[\"urn:params:core:2.0:User\",\"urn:params:core:3.0:User\"],\"userName\":\"ajklmnop_699100\",\"manager\":{\"value\":\"string\",\"$ref\":\"sdkoirk\",\"displayName\":\"string\",\"$Ref\":\"sdkweoirk\"},\"division\":\"string\",\"organization\":\"string\",\"costCenter\":\"string\",\"employeeNumber\":\"string\"}\n"
+ "";
AppJson appJson = objectMapper.readValue(jsonString, AppJson.class);
System.out.println("json " + appJson.getSchemas());
Here you will get the schemas.
I am posting an array in android retrofit I have to send the data of three fields in an array but I am not understanding how to do that I am successfully getting these three fields data but I am confused how to post this in an array can any one please help me with the sample code. thanks in advance.
profile_base64 = {
name : abc.jpg
type : image/jpg
string : 8323583475dsfsdbvcnwe
};
I have to post array of name profile_base64 and then in this array I have to send the data of three fields like name type and string
API call
HashMap<String, Object> map = new HashMap<>();
map.put("profile_base64", new Model("abc.jpg","image/jpg","8323583475dsfsdbvcnwe"));
JsonParser jsonParser = new JsonParser();
Call<RestResponse<AccessToken>> call = apiInterface.apiName((JsonObject) jsonParser.parse(gson.toJson(map)));
Model.java
public class Model {
private String name;
private String type;
private String string;
public Model(String name, String type, String string) {
this.name = name;
this.type = type;
this.string = string;
}
}
I want to be able to have different names for serialized and deserialized json objects when using jackson in java.
To be a bit more concrete: I am getting data from an API that is using one name standard on their JSON attributes, but my endpoints use a different one, and as I in this case just want to pass the data along I would like to be able to translate the attributes to my name standard.
I have read similar questions on here, but I simply can't seem to get it working.
private String defaultReference;
#JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
public void setDefaultReference(String defaultReference)
{
this.defaultReference = defaultReference;
}
#JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
That is my latest attempt. problem with this is that it always returns null, so the setter is not used.
I have also tried:
#JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
private String defaultReference;
#JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
This sort of works. It can deserialize default_reference. Problem is that in my JSON response I get both default_reference and defaultReference. Preferably I would only get defaultReference.
Has anyone done anything similar and see what is wrong with what I've tried?
You're on the right track. Here's an example of this working with a test JSON document.
public static class MyClass {
private String defaultReference;
#JsonProperty(value = "default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
#JsonProperty(value = "defaultReference")
public String getDefaultReference() {
return defaultReference;
}
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
MyClass instance = objectMapper.readValue("{\"default_reference\": \"value\"}", MyClass.class);
objectMapper.writeValue(System.out, instance);
// Output: {"defaultReference":"value"}
}
}
Another Alternative is
#JsonSetter("default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
#JsonGetter("defaultReference")
public String getDefaultReference() {
return defaultReference;
}
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);