Parsing inserted json object android - java

Sorry for my english. I try parsing inserted json, in my example i have this json:
{
"myTable": {
"1": {
"type": "1",
"category": "1",
"body": {
"2": {
"id": "2",
"device_name": "test 1"
},
"5": {
"id": "5",
"device_name": "test 2"
}
}
},
"2": {
"type": "2",
"category": "1",
"body": {
"6": {
"id": "6",
"device_name": "test 3"
}
}
}
}
}
Its json object to json object. This put me stumped. Bellow my try code parse this json
JSONObject sensorTypes = json.getJSONObject("myTable");
if(sensorTypes.length() > 0) {
Iterator<String> iterasensorTypes = sensorTypes.keys();
while(iterasensorTypes.hasNext()) {
String currentKey = iterasensorTypes.next();
JSONObject obj = sensorTypes.optJSONObject(currentKey);
if(obj != null) {
Log.e("type", obj.getString("type"));
Log.e("category", obj.getString("category"));
JSONObject sensor = json.getJSONObject("body");
if(sensor.length() > 0) {
Iterator<String> iteratorSensor = sensor.keys();
while( iteratorSensor.hasNext() ) {
String currentKeySensor = iteratorSensor.next();
JSONObject objSensor = sensor.optJSONObject(currentKeySensor);
if(objSensor != null) {
Log.e("device_name", objSensor.getString("device_name"));
}
}
}
}
}
}
And i have this:
org.json.JSONException: No value for body
UPD:
My log:
E/type﹕ 1
E/category﹕ 1
E/ get﹕ org.json.JSONException: No value for body

You are using json.getJSONObject("body"); instead of obj.getJSONObject("body");, json is the top object, the one with the key myTable. body is inside the children of myTable, the ones you iterate through and reference using the obj object JSONObject obj = sensorTypes.optJSONObject(currentKey);

Instead of
JSONObject sensor = json.getJSONObject("body");
use
JSONObject sensor = obj.getJSONObject("body"); //changed to obj from json

Related

how to covert JSONObject to another Required JSONObect by mapping AccountId using java

**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)

Json data parsing and display in List using Codename one

Here I have to parse JSON data getting from Facebook and display in list using Codename one so how can I cast ArrayList with Map.
Here is my Json data
{
"posts": {
"data": [
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-14T19:08:34+0000",
"id": "1323317604429735_1307213186040177"
},
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-02T14:22:50+0000",
"id": "1323317604429735_1295671703860992"
},
{
"message": "Hurray....... INDIA WON KABBADI WORLD CUP 2016",
"created_time": "2016-10-22T15:55:04+0000",
"id": "1323317604429735_1182204335207730"
},
{
"story": "Gaurav Takte updated his profile picture.",
"created_time": "2016-10-21T05:35:21+0000",
"id": "1323317604429735_1180682575359906"
},
{
"message": "Friends like all of you … I would love to keep forever.
#oldmemories with # besties
#happydays",
"story": "Gaurav Takte with Avi Bhalerao and 5 others.",
"created_time": "2016-10-21T05:33:55+0000",
"id": "1323317604429735_1180682248693272"
},
{
"message": "\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.
तुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना
सुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच
बाप्पाच्या चरणी प्रार्थना. \"
गणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!",
"story": "Gaurav Takte with Avi Bhalerao and 18 others.",
"created_time": "2016-09-05T05:06:58+0000",
"id": "1323317604429735_1133207030107461"
}
]
}
}
So how can I parse it and also display in list manner in Codename one.
Check out the JSONParser class in Codename One which the developer guide covers.
The sample from the guide is pasted below but I suggest reading it there as it is properly annotated there:
Form hi = new Form("JSON Parsing", new BoxLayout(BoxLayout.Y_AXIS));
JSONParser json = new JSONParser();
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), "/anapioficeandfire.json"), "UTF-8")) {
Map<String, Object> data = json.parseJSON(r);
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
String url = (String)obj.get("url");
String name = (String)obj.get("name");
java.util.List<String> titles = (java.util.List<String>)obj.get("titles");
if(name == null || name.length() == 0) {
java.util.List<String> aliases = (java.util.List<String>)obj.get("aliases");
if(aliases != null && aliases.size() > 0) {
name = aliases.get(0);
}
}
MultiButton mb = new MultiButton(name);
if(titles != null && titles.size() > 0) {
mb.setTextLine2(titles.get(0));
}
mb.addActionListener((e) -> Display.getInstance().execute(url));
hi.add(mb);
}
} catch(IOException err) {
Log.e(err);
}
hi.show();
Try this,
JSONObject obj=new JSONObject(response);
JSONObject posts_obj=obj.getJSONObject("posts");
JSONArray data_arr=posts_obj.getJSONArray("data");
for(int i=0;i<data_arr.length();i++) {
JSONObject data_obj=data_arr.getJSONObject(i);
String story = data_obj.getString("story");
String created_time = data_obj.getString("created_time");
String id = data_obj.getString("id");
if(data_obj.has("message")) {
String message = data_obj.getString("message");
}
}

Parse JSON File and iterate over specific parameters

where I want to check which elements of the 1st file are missing in the second one.
Here is the form of the first one:
[
{
"pId": "pId1",
"Platform":["ios","and","web","winph","win"],
"Name": "ay",
"ShortDescription": "Mobi",
"Detail" : {
"IncentiveInformation": "ppp",
"DisplayName" : "vvv!",
"Description" : "mmm",
"TermsAndConditions": ".."
}
},
{
"pId": "pId2",
"Platform":["afasd","sdfsd","pppp","asdas","win"],
"Name": "ay",
"ShortDescription": "mob",
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:01","2015.01.01-23:59"],
"IncentiveInformation": "PRO",
"Name": "iTunes",
"ShortDescription": "Punkte sammeln bei iTunes",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "urlHere",
"JumpToShopName" : "Zu iTunes"
}
},
{
"pId": "pId3",
"Platform":["wqdsa"],
"Name": "poti",
"ShortDescription": "pun",
"ImageURL": "url.here",
"Promotion" : false,
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:00","2015.01.01-23:59"],
"IncentiveInformation": "ppeur",
"Name": "namehere",
"ShortDescription": "tune",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "noq",
"JumpToShopName" : "Zu"
}
}
]
and here is the form of the 2nd one:
{
"pList": [{
"shortName": "bb",
"longName": "bb",
"pId": "pId2",
"featured": true,
"pLog": "url.here",
"incentivation": "eu",
"details": {
"teaserImage": "image.url",
"description": "desc here",
"jumpToShopURL": "nurl",
"jumpToShopButton": "zubay",
"terms": [{
"headline": "Wichtig",
"body": "bodyline"
}]
}
}, {
"shortName": "one short name",
"longName": "bkp",
"pId": "pId1",
"featured": true,
"pLo": "some.pLo",
"incentivation": "1p",
"details": {
"teaserImage": "some.url",
"description": "desc",
"jumpToShopURL": "short url",
"jumpToShopButton": "Zuay",
"terms": [{
"headline": "Wichtig",
"body": "bodyhere"
}]
}
}]
}
Si I thought to save all the "pId" of the first one in a List(or array) and then iterate over that list and check for each one if the pId exists in the new one.
So I tried this, but it is not working..
Could anyone help me with that? I tried a bit and then I found that I have too many difficulties, to get the pIds saved in a list or an array.
So has someone an idea?
import java.io.*;
import org.json.*;
public class MainDriver {
public static void main(String[] args) throws JSONException {
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONObject jobj = new JSONObject(jsonData);
JSONArray jarr = new JSONArray(jobj.getJSONArray("pList").toString());
for(int i = 0; i < jarr.length(); i++)
System.out.println("id: " + jarr.getString(i));
}
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
For the 2nd form, you have an JSONObject, but it contains some errors. Please fix them, or use a the 1st form again.
SOLUTION
I found some errors in the second file so I suggest the following edits:
change "jumpToShopURL": nurl", to "jumpToShopURL": null,
add a comma at the end of "description": "desc"
add a comma at the end of "jumpToShopURL": "short url"
For the code, you can use the following lines:
/*first file*/
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONArray jarr = new JSONArray(jsonData);
/*array of first file's ids*/
ArrayList<String> srcArray = new ArrayList<>();
for(int i = 0; i < jarr.length(); i++) {
srcArray.add(jarr.getJSONObject(i).getString("pId"));
}
/*second file*/
// second form in a seperate file
JSONObject obj = new JSONObject(readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt2.json"));
JSONArray arr = obj.getJSONArray("pList");
/*array of second file's ids*/
ArrayList<String> dstArray = new ArrayList<>();
for(int i = 0; i < arr.length(); i++) {
dstArray.add(jarr.getJSONObject(i).getString("pId"));
}
for (String string : srcArray) {
if (dstArray.indexOf(string)==-1)
System.out.println(string + " is missing in the second file");
}
Luckily for you there are already developed libraries to parse any JSON string, like the one's you provided. One of the most popular is
org.json
Using this you can write code similar to this:
import org.json.*;
String myString = ".." // The String representation you provided
JSONObject obj = new JSONObject(myString);
JSONArray arr = obj.getJSONArray("pList");
Another popular library for the same task is GSON
One possible solution using Jackson is the following:
private static final String JSON1 = // first json;
private static final String JSON2 = //second json;
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap> list1 = Arrays.asList(mapper.readValue(JSON1, LinkedHashMap[].class));
List<LinkedHashMap> list2 = Arrays.asList(mapper.readValue(mapper.readTree(JSON2).get("pList").toString(), LinkedHashMap[].class));
List<LinkedHashMap> missingItens = new ArrayList<>();
for (LinkedHashMap o1 : list1) {
if (!objectExistsInList(o1.get("pId").toString(), list2)) {
missingItens.add(o1);
}
}
}
private static boolean objectExistsInList(String pIdValue, List<LinkedHashMap> objs) {
for (LinkedHashMap map : objs) {
if (map.containsValue(pIdValue)) {
return true;
}
}
return false;
}
Please keep in mind this is a very specific implementation to the given JSONs.

How to fetch all the nodes and child nodes of JSON object in java?

I want to fetch all the nodes of the below JSON object. For example
result, identification, payment etc.
{
"result": {
"identification": {
"transactionid": "Merchant Assigned ID",
"uniqueid": "d91ac8ff6e9945b8a125d6e725155fb6",
"shortid": "0000.0005.6238",
"customerid": "customerid 12345"
},
"payment": {
"amount": "2400",
"currency": "EUR",
"descriptor": "order number"
},
"level": 0,
"code": 0,
"method": "creditcard",
"type": "preauthorization",
"message": "approved",
"merchant": {
"key1": "Value1",
"key0": "Value0"
}
},
"id": 1,
"jsonrpc": "2.0"
}
I have used the following code:
JSONObject partsData = new JSONObject(returnString);
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String result=iterator.next();
System.out.println(result);
}
But the result I am getting is:
id
result
jsonrpc
How do I get all the node names?
Move your iterator logic (to iterate over json) in a method
e.g.,
public Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
if ( json.getJSONObject(key) instanceof JSONObject ) {
JSONObject value = json.getJSONObject(key);
parse(value,out);
}
else {
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
This way you can check for each sub node in the json object.
You have to parse through all the objects.
JSONObject partsData = new JSONObject("result");
JsonObject identification = partsData.getJsonObject("identification");
JsonObject payment = partsData.getJsonobject("payment");

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Categories