How I can deserialize a json object without a name and dynamic? - java

I have this JSON:
{
"username": [
"A user with that username already exists."
],
"ruc": [
"user with this ruc already exists."
],
"code": [
"user with this code already exists."
],
"document_number": [
"user with this document number already exists."
]
}
The name of the properties will be dynamic and the length of the JSON too.
I'm using GSON tool and I create a POJO but without a name, I cant reference to this, that's, why I received that myError instance, is null.
This is my POJO
public class MyError {
public Map<String, Object> message = new HashMap<>();
}
And this is my GSON code
myError = new Gson().fromJson(response.errorBody().string(), MyError.class);
And I want to show a message for every item like this:
for (String key : myError.message.keySet()) {
Utils.showToast(getBaseContext(), "Message: " + myError.message.get(key) + " Field: " + key);
}

You can try to use this:
Map myError = new Gson().fromJson(s, Map.class);
Or if you want to use your class json should look like:
{
"message": {
"username": [
"A user with that username already exists."
],
"ruc": [
"user with this ruc already exists."
],
"code": [
"user with this code already exists."
],
"document_number": [
"user with this document number already exists."
]
}
}

Consider using Gson and java native JsonParser.

Related

Iterate over Laravel validation errors object in java

I have an android app that uses laravel as backend. I validate user inputs in laravel using Validator facades.
$validator = Validator::make($inputs, $rules);
if ($validator->fails()) {
return response(['errors' => $validator->errors()], 401);
}
The response is an json object that could have different elements.
{
"errors": {
"username": [
"The username has already been taken.",
"The username format is invalid."
],
"email": [
"The email has already been taken."
]
}
}
or
{
"errors": {
"password": [
"The password must have at least 8 characters."
]
}
}
I get the JSONObject in the android app using java.
JSONObject errors = jsonObject.getJSONObject("errors");
My question is that how can I iterate over the errors object to show the errors?

JSON object is getting removed with remove method in JSON file instead of JSON array [duplicate]

This question already has answers here:
How to remove an element from JSON string in Java?
(2 answers)
Closed 6 months ago.
I am trying to remove JSON array from a JSON file using org.json library
I am trying to remove webAutomation JSON array from the JSON file as follows
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"webAutomation": [
{
"price": "500",
"courseTitle": "Selenium"
},
{
"price": "333",
"courseTitle": "Protractor"
}
],
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}
I tried following code. Here str has JSON file
JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);
This is removing the whole JSON object instead of just JSON Array.
The output is {"empty":false}
Please help
You can use remove method in org.json.JSONObject#remove.
JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);
The output will be:
{
"instructor": "Test_Instructor",
"url": "www.google.com",
"services": "Test Automation Service",
"expertise": "Testing",
"linkedIn": "linkedIn",
"courses": {
"apiAutomation": [
{
"price": "344.00",
"courseTitle": "Rest Assured API Automation"
}
],
"mobileAutomation": [
{
"price": "4555",
"courseTitle": "Appium"
}
]
}
}

How to find a key in a JSON file with Gson library?

Given a JSON file which looks like the code below, how can I find a specific key with its corresponding value without hard-coding the structure in a Java class or otherwise. Let's say I want to get "Signal_Settings" as a JSON Object but given the possibility of changes in the JSON file structure I want to get this object regardless for example by iterating through all keys in the file. I have tried to do this iteratively and failed, so I think a recursive function is the way for which I didn't find a solution yet. My iterative code looks like this:
while (true) {
try {
for(Map.Entry<String, JsonElement> entry:newJsonObj.entrySet()){
System.out.println(entry.getKey());
System.out.println("Before NewJsonObj:" + newJsonObj);
newJsonObj = newJsonObj.getAsJsonObject(entry.getKey());
System.out.println("After NewJsonObj:" + newJsonObj + "\n");
//tempEntrySet = newJsonObj.entrySet().iterator().next();
}
//System.out.println("Key:" + tempEntrySet.getKey());
//System.out.println("TempEntry:" + tempEntrySet);
}catch (Exception e){
break;
}
}
and the JSON file:
{
"config2": {
"UDP_Settings": {
"ListenAddress": "'127.0.0.1'",
"ListenPort": "54523"
},
"Signal_Settings": {
"Count": 1,
"Signals": [
{
"Name": "time",
"Type": "uint8",
"Interval": "foo",
"Description": "",
"Unit": null
},
{
"Name": "othersignal",
"Type": "uint8",
"Interval": "fff",
"Description": "",
"Unit": null
}
]
},
"Tag_Settings": null,
"Model_Settings": null
}
}

Unable to get specific data from a JSON object

I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

gson json parser: value without key

I want to parse a json structure like this:
{"response":
{
"arr1":[count,{...}],
"arr2":[count,{...}]
}
}
Everything is ok if count have key "count" (for example). But the key is blank. Is it any way to map this structure and manually retrive only this value or i need to parse all of this json myself without gson ?
UPDATED
Here is a valid json (checked with http://jsonlint.com/)
{
"response": {
"arr1": [
615,
{
"body": "hi",
"title": "Re(2): ..."
},
{
"body": "hello",
"title": "Re(23): ..."
}
],
"arr2": [
132,
{
"body": "hi",
"title": "Re(2): ..."
},
{
"body": "hello",
"title": "Re(23): ..."
}
]
}
}
If you want to parse arbitrary collections you should read Serializing and Deserializing Collection with Objects of Arbitrary Types and look at the example code example code.

Categories

Resources