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.
Related
I try to create java json array ,
can't find any way to create them using Nashorn
i can create simple objects ...
private void createJsonObject() {
try {
final Map<String, Object> newMap = new HashMap<>();
newMap.put("foo",1);
newMap.put("bar", true);
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.putAll(newMap);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result : {"bar":true,"foo":1}
Here i try to create array but im getting empty json
private void createJsonObject() {
try {
List<String> returnList = new ArrayList<>();
returnList.add("x");
returnList.add("y");
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.put("test",returnList);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result: {}
The end goal is to build array of objects in memory using java native tools without using dependencies
I have a class like
data class Data(
val field1: Int = 123
val field2: String = "Foo"
)
I have JSON like
{"field1": 123, "field2": "Foo"}
How can I check if my JSON really represents the structure of the class using Google GSON?
Hi bro there are several Ways first by using code
import org.json.*;
public boolean isValidJSONTest(String yourjsonString) {
try {
new JSONObject(yourjsonString);
} catch (JSONException ex) {
try {
new JSONArray(yourjsonString);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
For Gson code is like
Gson gson = new Gson();
try {
Object o = gson.fromJson(json, Object.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(o));
} catch (Exception e) {
System.out.println("invalid json format");
}
second you can use browser console and paste your string in console and enter
third they are several website that can validate json format or view etc
https://jsonlint.com/
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
This is the first time I am facing a very weird problem. I have a JSONObject mentioned below.:
Link for the JSON body (Cant paste JSON body here because of character limit):
http://kolam.vicz.in:7890/games_gifs/
I am parsing the above set of JSONObjects and converting them to Java objects. Below is my code of parsing this JSON body.
private void getGameList() {
StringRequest request = new StringRequest(Request.Method.GET, gameUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject mainObject = new JSONObject(response);
JSONArray gamesArray = mainObject.getJSONArray("TracingGames");
Log.e(TAG, "gameArray length:" + gamesArray.length());
for (int i = 0; i < gamesArray.length(); i++) {
JSONObject obj = gamesArray.getJSONObject(i);
for (String str : getKeys(obj)) {
Log.e(TAG, str);
if (str.equalsIgnoreCase("kolam")) {
/*Section for Learn and Kolam Tracing games start*/
//TODO: Need to add the game names to the object (Need server side implementation as well)
KolamTracingGames kolamTracingGames = new KolamTracingGames();
kolamTracingGames.setKolamGifPath(obj.getString("path"));
kolamTracingGames.setKolamLevel(Integer.parseInt(str));
kolamTracingGames.setKolamGameName("Kolam Tracing");
kolamTracingGames.setX(getXCoordinates(obj));
kolamTracingGames.setY(getYCoordinates(obj));
kolamObjects.add(kolamTracingGames);
break;
} else if (str.equalsIgnoreCase("level")) {
LearnTracingGames learnTracingGames = new LearnTracingGames();
learnTracingGames.setLearnGameGifPath(obj.getString("path"));
learnTracingGames.setLearnGameLevel(Integer.parseInt(str));
learnTracingGames.setGameName("Learn Game");
learnTracingGames.setX(getXCoordinates(obj));
learnTracingGames.setY(getYCoordinates(obj));
learnGameObjects.add(learnTracingGames);
Log.e(TAG, learnGameObjects.size() + "");
break;
}
}
}
if (gameType.equalsIgnoreCase("Trace the Kolam")) {
kolamTraceAdapter = new KolamTraceAdapter(getActivity());
kolamTraceAdapter.getGameList(kolamObjects);
recyclerView.setAdapter(kolamTraceAdapter);
} else if (gameType.equalsIgnoreCase("Learn")) {
learnGameAdapter = new LearningGameAdapter(getActivity());
learnGameAdapter.getGameList(learnGameObjects);
Log.e(TAG, "learngameobject size:" + learnGameObjects.size());
recyclerView.setAdapter(learnGameAdapter);
Log.e(TAG, "Learn games");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage());
if (getActivity() != null) {
Alerter.create(getActivity())
.setTitle(R.string.warning)
.setText(R.string.network_error)
.setDuration(2000)
.setBackgroundColorRes(R.color.dot_dark_screen1)
.show();
}
}
});
request.setTag(TAG);
request.setRetryPolicy(new DefaultRetryPolicy(30000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(request);
My problem is there are 8 level type objects and 4 kolam objects (Please refer the JSON body for clarity). I am having two separate POJO classes for them. I am able to parse the JSON body properly but when I am trying to create Java objects of those JSONObjects the inner most for loop is not running completely. Its stopping after 1 loop.
the inner for loop is not getting executed completely (executing only once but should get executed more then 12 times) if I am doing this (Creating Java Objects):
for (int i = 0; i < gamesArray.length(); i++) {
JSONObject obj = gamesArray.getJSONObject(i);
for (String str : getKeys(obj)) {
Log.e(TAG, str);
if (str.equalsIgnoreCase("kolam")) {
/*Section for Learn and Kolam Tracing games start*/
//TODO: Need to add the game names to the object (Need server side implementation as well)
KolamTracingGames kolamTracingGames = new KolamTracingGames();
kolamTracingGames.setKolamGifPath(obj.getString("path"));
kolamTracingGames.setKolamLevel(Integer.parseInt(str));
kolamTracingGames.setKolamGameName("Kolam Tracing");
kolamTracingGames.setX(getXCoordinates(obj));
kolamTracingGames.setY(getYCoordinates(obj));
kolamObjects.add(kolamTracingGames);
break;
} else if (str.equalsIgnoreCase("level")) {
LearnTracingGames learnTracingGames = new LearnTracingGames();
learnTracingGames.setLearnGameGifPath(obj.getString("path"));
learnTracingGames.setLearnGameLevel(Integer.parseInt(str));
learnTracingGames.setGameName("Learn Game");
learnTracingGames.setX(getXCoordinates(obj));
learnTracingGames.setY(getYCoordinates(obj));
learnGameObjects.add(learnTracingGames);
Log.e(TAG, learnGameObjects.size() + "");
break;
}
}
}
the getKeys(JSONObject) method is below:
private static String[] getKeys(JSONObject firstJSONObject) {
Iterator keysToCopyIterator = firstJSONObject.keys();
List<String> keysList = new ArrayList<>();
while (keysToCopyIterator.hasNext()) {
String key = (String) keysToCopyIterator.next();
keysList.add(key);
}
return keysList.toArray(new String[keysList.size()]);
}
But If I avoid creating objects inside the for loop then the inner for loop runs completely.
But If I avoid creating objects inside the for loop then the inner for
loop runs completely.
Integer.parseInt("level") or Integer.parseInt("kolam") which is clearly a crash
Explanation
when your any of if (str.equalsIgnoreCase("kolam")) or else if (str.equalsIgnoreCase("level")) { matches then
you clearly have a crash here , Integer.parseInt(str) because str will either be level or kolam which are clearly not integers
Solution : Don't use str instead fetch the values
if (str.equalsIgnoreCase("kolam")) {
//... code
kolamTracingGames.setKolamLevel(obj.optInt(str));
//... code ^^^^^^^^^^^^^^^
break;
} else if (str.equalsIgnoreCase("level")) {
//... code
learnTracingGames.setLearnGameLevel(obj.optInt(str));
//... code ^^^^^^^^^^^^^^^
break;
}
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.