Parse simple JSON - java

I have a trouble to parse this piece of JSON
{
"00408C88A2E6": {
"id": "00408C88A2E6",
"name": "pippo"},
"00408C91188B": {
"id": "00408C91188B",
"name": "pluto"
},
"00408C944B99": {
"id": "00408C944B99",
"name": "minni"
},
"00408C944BA0": {
"id": "00408C944BA0",
"name": "topolino"
}
I need to get all the key "id" and "name", I tried with an iterator but I was able to retrive just the first dicts (00408C88A2E6,00408C91188B...), could anyone give me any hint?
Thank you
Edit:
I'm using org.json and to parse this I tried in this way
JSONObject jsonChannels = getHttpJson(url_user_cam);
ArrayList<String> al = new ArrayList<String>();
Log.i(LOG_TAG, jsonChannels.toString());
try{
Iterator<String> iterator = jsonChannels.keys();
while (iterator.hasNext() ){
al.add(iterator.next());
}
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
with this piece of code my intent is to get the first dict ("00408C88A2E6") after make it I need to access to "id" and "name" element, hwo can i do it?

As pointed in the comments, it looks like your JSON is incomplete. Maybe a pasting error ?
Do you do it manually or do you use a library ?
Have you tried using the "official" Java JSON package ?

Related

How to modify the value of a particular field in a JSON file using json-simple, after parcing the JSON file

I need to modify a particular value of a key in my json file, it is a nested JSON file and i have traversed till that key value pair but i'm not able to modify the value and don't know how to write back to the json.
Using json-simple to parse the JSON
This is the JSON file:
{
"entity": {
"id": "ppr20193060018",
"data": {
"relationships": {
"productpresentationtolot": [
{
"id": "",
"relTo": {
"id": "",
"data": {
"attributes": {
"rmsitemid": {
"values": [
{
"source": "internal",
"locale": "en-US",
"value": "2019306"
}
]
}
}
},
"type": "lot"
}
}
]
}
},
"type": "productpresentation"
}
}
Reading it using below code:
JSONParser parser = new JSONParser();
reader = new FileReader("path.json");
JSONArray rmsArray =(JSONArray) rmsitemid.get("values");
for(Object obj2:rmsArray)
{
JSONObject tempObj1=(JSONObject)obj2;
System.out.println(tempObj1.get("value"));
}
I'm able to print what is there in value(Key) i.e., 2019306 but i don't have any idea how can i replace it with some other value and it should change the value in JSON file also.
Any help appreciated!
Here is a complete exmaple how to read and write using the simple-json library:
// read from resource file
JSONObject value;
try (Reader in = new InputStreamReader(getClass().getResourceAsStream("/simple.json"))) {
JSONParser parser = new JSONParser();
value = (JSONObject) parser.parse(in);
}
JSONObject entity = (JSONObject) value.get("entity");
// update id
entity.put("id", "manipulated");
// write to output file
try (Writer out = new FileWriter("output.json")) {
out.write(value.toJSONString());
}
The JSONObjects are basically Maps. So you can just put values inside.
In order to create a JSON string again, use toJSONString().
In my example, I create a new output file. You could also override the original input file, though. But you have to write the file completely.

Remove duplicated in base Unique JSONObjects in JSONArray

How Remove duplicated JSONObjects in JSONArray java android
I have this code and I do not know how to remove duplicates, according to the duplicate value of number and time of arrays strings objects, but but I do not know how to do it, I'm a bit confused with arrays
[
{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:06 PM",
"type": "all"
},
{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:06 PM",
"type": "all"
},
//Duplicatedhowremovethisifnumberisequalandtime{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:07 PM",
"type": "all"
}
]
I would appreciate your help
JSON parser by default allows duplicates so there is no direct way to remove the duplicates. However, there are ways to deal with this. You can validate JSON against schema.
If using Jackson, here is the setting which will help you to detect duplicates:
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
You need to use set data structure. Set store unique objects. If you have custom objects, you need to override equals method and hash code method.
I got the solution, i shared you
String getloglist = sp.getString(Constant.LOG, "");
ArrayList<String> listdata = new ArrayList<String>();
try {
// Load the data from json
JSONArray jsonArraylogs= new JSONArray(getloglist);
if (jsonArraylogs != null) {
for (int i=0;i<jsonArraylogs.length();i++){
listdata.add(jsonArraylogs.getString(i));
//Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();
ArrayList<String> values=new ArrayList<String>();
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(listdata);
listdata.clear();
listdata.addAll(hashSet);
Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();

Parsing nested json array in java

I have json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.
The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.
Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1

AngularJS: passing complex json data using $http.post

I'm having trouble passing a complex json object in angularjs with $http.post. I'm keep getting a 400 bad request error sent back from the server saying the request was syntactically incorrect. I believe it has something to do with the array since it passes fine when i don't include it.
json i'm passing.
{
customer: {
firstName: "John",
lastName: "Doe",
street: "1234 South Dr",
city: "Detroit",
state: "MI",
zip: "12345",
phone: "123-321-1234",
email: "EMAIL#GMAIL.COM"
},
order: {
orderDate: "06-16-2015",
registerNum: "1",
transactionNum: "7820",
deliveryStatusID: 1,
notes: "Hold order until July",
items: [
{skuID: "1234568",
skuDescription: "Order item 1",
qty: "4",
itemStatusID: 1,
itemStatusDescription: "Backorder"
},
{skuID: "7387491",
skuDescription: "Order item 2",
qty: "1",
itemStatusID: 1,
itemStatusDescription: "Flagged"
}
]
}
}
angular service function
this.addOrder = function(new_order) {
return $http.post(base + "/add", new_order);
};
Spring MVC controller method
#RequestMapping(value="/add", method=RequestMethod.POST)
public void addOrder(#RequestBody CustomerOrder customerOrder) {
System.out.println("----CUSTOMER-INFO----");
System.out.println(customerOrder.getCustomer().getFirstName());
System.out.println(customerOrder.getCustomer().getLastName());
System.out.println("");
System.out.println("----ORDER-INFO----");
System.out.println(customerOrder.getOrder().getOrderID());
System.out.println(customerOrder.getOrder().getOrderDate());
}
The problem only seems to occur when I pass the items array in the json. I've passed the same json object without the items array and it works fine. The format of the json is being sent in the same format that gets returned whenever I GET an order with my angularjs service method so I'm really not sure as to where I'm going wrong with this.
If I need to provide more code please let me know. I appreciate any effort in helping me out.
Thank you.
Jason
Well after struggling to find my error in this problem, I finally found a solution. I thought I'd share how I debugged and fix this problem in case someone else is in a similar situation as I was.
After trying every possible way of sending my data in angular to the server and continually getting the same HTTP 400 error, I decided to send the json as a string and accept the json as a string in my spring mvc controller like this.
angular service method:
this.addOrder = function(new_order) {
return $http.post(base + "/add", angular.toJson(new_order));
};
spring controller
#RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(#RequestBody String json) {
}
From here I simply took the json passed in and used the Jackson ObjectMapper to convert the json string to my POJO like this.
mapping json string to pojo
#RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(#RequestBody String json) {
ObjectMapper mapper = new ObjectMapper();
try {
CustomerOrder order = mapper.readValue(json, CustomerOrder.class);
System.out.println(order.getCustomer().getFirstName() + " " + order.getCustomer().getLastName());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
After doing this and running my code, I would get an UnrecognizedPropertyException on a field in my Items class when trying to bind the items json to the List in my Order class. It was just a simple mispelling on the json side and I completely missed it. After correcting this, jackson mapped everything correctly and I no longer get this HTTP 400 Error The request was syntactically incorrect.
Another thing to note is that if you pass your object as a string in angular using the JSON.stringify you may encounter this same exception on hashKey field in the JSON object. The hashKeys are used by angular to monitor changes. I believe you can use a jackson annotation to ignore unknown fields or you can simply use angular.toJson instead which will remove all the hasKey/values for you which is what I did.
Just formatted the Json in a better way. Try this if it helps. Also, post the java classes if possible:
{
"customer": {
"firstName": "John",
"lastName": "Doe",
"street": "1234 South Dr",
"city": "Detroit",
"state": "MI",
"zip": "12345",
"phone": "123-321-1234",
"email": "EMAIL#GMAIL.COM"
},
"order": {
"orderDate": "06-16-2015",
"registerNum": "1",
"transactionNum": "7820",
"deliveryStatusID": 1,
"notes": "Hold order until July",
"items": [
{
"skuID": "1234568",
"skuDescription": "Order item 1",
"qty": "4",
"itemStatusID": 1,
"itemStatusDescription": "Backorder"
},
{
"skuID": "7387491",
"skuDescription": "Order item 2",
"qty": "1",
"itemStatusID": 1,
"itemStatusDescription": "Flagged"
}
]
}
}

JSON different objects in an array

At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")

Categories

Resources