net.sf.json.JSONException: There is a cycle in the hierarchy - java

I want to write the value of list in JSON File. But it's giving an exception.
JSONArray objJsonArray = null;
FileWriter objJsonFileWriter = null;
try {
objJsonArray = (JSONArray) JSONSerializer.toJSON(objList); //<- This line is giving net.sf.json.JSONException: There is a cycle in the hierarchy
objJsonFileWriter = new FileWriter("D:\\MyJson.json");
objJsonFileWriter.write(objJsonArray.toString());
objJsonFileWriter.flush();
objJsonFileWriter.close();
} catch (JSONException jse) {
jse.printStackTrace();
}
Please make me know how to get rid of this exception. I am doing this work using core Java

Thanks #Kevin for your valuable suggestion.
JSONArray objJsonArray = null;
FileWriter objJsonFileWriter = null;
PlayerMasterJsonInfoBean objBean = null;
try {
objList.setFirst_name(getPlayerMaster.getFirst_name()); //<- Get the value from bean class then add to collection class
objList.setLast_name(getPlayerMaster.getLast_name()); //<- Get the value from bean class then add to collection class
objJsonArray = (JSONArray) JSONSerializer.toJSON(objList); //<- Then pass object here
objJsonFileWriter = new FileWriter("D:\\MyJson.json");
objJsonFileWriter.write(objJsonArray.toString());
objJsonFileWriter.flush();
objJsonFileWriter.close();
} catch (JSONException jse) {
jse.printStackTrace();
}

Related

How to put in array the children of the children

private static JSONArray getListOfChildPagesAsJSON(Page page) {
JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
pagesArray.put(pageObject);
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
return pagesArray;
}
So that not only the children of the transferred page put into array, but also the children of the children.
This is a classical case for recursion, like reading directoy tree on filesystem. My suggestion is as follows:
First step: Change the scope of variable JSONArray pagesArray = new JSONArray(); from function to class scope.
public MyClass {
private JSONArray pagesArray = new JSONArray();
...
}
Step two: Change return value to void and the modifier of your function by removing static.
private void getListOfChildPagesAsJSON(Page page) { }
Step three add the missing recusion to your its body.
//JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
//Add the created object to your array which is class variable
this.pagesArray.put(pageObject);
//--Check for each single page for child pages again
Iterator<Page> childPagesOfChildpage = childPage.listChildren();
while (childPagesOfChildpage.hasNext()) {
getListOfChildPagesAsJSON(childPagesOfChildpage.next());
}
//--
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
Note: The check childPage.hasChild() does not work here, because the node jcr:content is a valid child of passed page.

Accessing the JSON data from the method in android

Example of class that will hold the properties in JSONObject and then return the object properties
class OperatorProperties {
JSONObject TigoProperties()
{
JSONObject property = new JSONObject();
try {
property.put("color", "#223f99");
property.put("logo", R.drawable.tigo);
}catch (JSONException e){
e.printStackTrace();
}
return property;
}
}
Problems, I don't know how to get the properties details from the JSONObejct
JSONObject d = OperatorProperties.TigoProperties();
operatorLogo.setImageResource(d);
Any help please because am just want every property should come from the JSONObject

How to throw a parseException in a switch statement?

To increase my projects code coverage, I need to reach the branch ParseException in this method:
public String filterMessage(String actionIn, String messageIn) {
String message = null;
try{
switch (actionIn) {
//EDIT: this calls the other class causing parseexception
case "search":
message = (srvmt.SearchEngine(messageIn));
break;
default:
message = messageIn;
break;
}
}catch (ParseException e) {
System.out.println("Encountered parse exception");
e.printStackTrace();
}catch(IOException ioException){
ioException.printStackTrace();
}
return message;
}
Instincts are that we must put a String that is "illegal", that can't be parsed because it isn't actually a String, but how do you place something like that without causing a compile error (like putting an int to cause faulse parsing). Any ideas how to test this catch "branch"?
EDIT: This is the method the case above calls which uses a parse exception
public String SearchEngine(String removecommand)
{//INCOMING-SEARCH¿Email¿#gmail.com
JSONArray databaseupdated = read(pathdatabase);
ArrayList<String> matchlist = new ArrayList<String>();
JSONObject mainobj = new JSONObject();
JSONArray userinfo = new JSONArray();
JSONObject obj = new JSONObject();
for(int i = 0; i<databaseupdated.size(); i++)
{
String option = "";
String value = "";
try {
JSONObject json = (JSONObject) new JSONParser().parse(removecommand);
option = (String) json.get("option");
value = (String) json.get("value");
mainobj= (JSONObject) new JSONParser().parse(databaseupdated.get(i).toString());
userinfo =(JSONArray) new JSONParser().parse(mainobj.get(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1)).toString());
obj = (JSONObject) new JSONParser().parse(userinfo.get(0).toString());
} //EDIT, there is a lot of code not explained, but here is the parse EXCEPTION
catch (ParseException e) {
return "false";
}
if(SearchEngineTRUEFALSE1(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1),option,value))
{
matchlist.add(obj.get("Email").toString());
}
}
return matchlist.toString();
}
Try this :
throw new ParseException("Parse exception description you want");
you could throw an exception as Michaël told and if you are using Junit to test, you could do something like this using the expected annotation to catch it
#Test(expected= ParseException)
public void testFilterMessage() {
filterMessage(illformedString1, illformedString2);
}
Given your updated question:
You want to look into using a mocking framework.
Basically you have to enable your class under test so that you can provide a mocked srvmt object to it. And you configure that mock to simply throw that exception upon calls to the method it owns. Well, one of your test case configures the mock to throw that exception; other testcases would configure the mock to return other results.
In other words: search for terms like "dependency injection" and "mocking"; study and apply.

Converting a Bundle that contains bundles to JSON

I have a bundle that I would like to convert to one big JSONObject so that I can send it through a web service later on. This main bundle contains mainly strings and integers, but it also contains another bundle, which in that contains bundles that have sets of 4 key value pairs.
Here is a diagram to clear up any confusion:
Code:
private JSONObject convertBundleToJSON(Bundle b)
{
//the main json object to be returned
JSONObject json = new JSONObject();
Set<String> keys = b.keySet();
for (String key : keys) {
try {
// json.put(key, bundle.get(key)); see edit below
json.put(key, JSONObject.wrap(b.get(key)));
} catch(JSONException e) {
//Handle exception here
Log.d("Convert Bund", e.toString());
}
}
JSONObject fvl = new JSONObject();
int i = 0;
//error right here - b is a bundle of bundles; trying to iterate through
Set<Bundle> bundles = (Set<Bundle>) b.get("field_value_list");
for (Bundle bun : bundles)
{
JSONObject f = new JSONObject();
try {
f.put("fld_value_decode", bun.get("fld_value_decode"));
f.put("fld_id", bun.get("fld_id"));
f.put("fld_value", bun.get("fld_value"));
f.put("fld_name", bun.get("fld_name"));
fvl.put(i+"",f);
i++;
} catch(JSONException e) {
//Handle exception here
Log.d("FVL Convert Bund", e.toString());
}
}
try {
json.put("field_value_list", fvl);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
But I get a casting exception at the error line. It doesn't like the cast between bundle and set. Any ideas or alternative ways to get around this?
Rather than doing this sophisticated way, you can simply achieve this by creating a model class which is parcelable.
Simply add those json to that model and further passing it, using it would be simpler.

IllegalArgumentException JSON

I am trying to put String[] in jsonObject and getting following error
java.lang.IllegalArgumentException: Invalid type of value. Type:
[[Ljava.lang.String;] with value: [[Ljava.lang.String;#189db56] at
com.ibm.json.java.JSONObject.put(JSONObject.java:241)
Please help me to resolve this.
Thanks
public JSONObject toJSONObject() {
JSONObject jsonObject = new JSONObject();
//Use reflection to get a list of all get methods
//and add there corresponding values to the JSON object
Class cl = dto.getClass();
logger.infoFormat("Converting {0} to JSON Object", cl.getName());
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("get")) {
logger.infoFormat("Processing method - {0}", methodName);
//Check for no parameters
if (method.getParameterTypes().length == 0) {
String tag = getLabel(method);
Object tagValue = new Object();
try {
tagValue = method.invoke(dto);
} catch (Exception e) {
logger.errorFormat("Error invoking method - {0}", method.getName());
}
if (method.getReturnType().isAssignableFrom(BaseDTO.class)) {
DTOSerializer serializer = new DTOSerializer((BaseDTO) tagValue);
jsonObject.put(tag, serializer.toJSONObject());
} else if (method.getReturnType().isAssignableFrom(List.class)) {
ListSerializer serializer = new ListSerializer((List<BaseDTO>) tagValue);
jsonObject.put(tag, serializer.toJSONArray());
} else {
if (tagValue != null) jsonObject.put(tag, tagValue);
}
}
}
}
return(jsonObject);
}
try
jsonObject.put("yourKey", Arrays.asList(yorStringArray));
As you should read the manual first http://www.json.org/javadoc/org/json/JSONObject.html there is no variation of it expects an Object[]
Maybe you should take a look at google-gson.
I like it very much to work with json in Java.

Categories