how to create a Json String in blackberry - json

How i create an Json array like -
{"genres":[{"genre":[{"code":"CTY","name":"Country"}]},{"genre":[{"code":"HOP","name":"Hip Hop"}]}]}

download json api from following link:
https://github.com/upictec/org.json.me/
Create JSOn Object by using:
JSONObject obj=new JSONObject();
obj.put("key", value);
here value may be any primitive type String, int, boolean, long...

JSONObject jArrayFacebookFriendsData = new JSONObject();
JSONObject jObjectData = new JSONObject();
try {
jObjectData.put("friend_name",name_);
jObjectData.put("friend_id", id_);
jObjectData.put("friend_email", "null");
jObjectData.put("friend_phone", "null");
jArrayFacebookFriendsData.accumulate("friends",jObjectData);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference

Every time I open my app it crashes because of this error I dont know what should I do please help me... I have also attached logcat screen shot below and the java class in which the error is comming.
DataParser.java:
public class DataParser {
private HashMap<String,String> getPlace(JSONObject googlePlacesJson){
HashMap<String,String> googlePlaceMap=new HashMap<>();
String placeName="-NA-";
String vicinity="-NA-";
String latitude="";
String logitude="";
String reference="";
List<HashMap<String,String>> placesList=new ArrayList<>();
try {
if(!googlePlacesJson.isNull("name")){
placeName=googlePlacesJson.getString("name");
}
if (!googlePlacesJson.isNull("vicinity")){
vicinity=googlePlacesJson.getString("vicinity");
}
latitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
logitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference=googlePlacesJson.getString("reference");
googlePlaceMap.put("name",placeName);
googlePlaceMap.put("vicinity",vicinity);
googlePlaceMap.put("lat",latitude);
googlePlaceMap.put("lng",logitude);
googlePlaceMap.put("reference",reference);
} catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;
}
private List<HashMap<String,String>> getPlaces(JSONArray jsonArray){
long count;
count=jsonArray.length(); // error comes on this line
List<HashMap<String,String>> placesList=new ArrayList<>();
HashMap<String,String> placeMap=null;
for(int i=0;i<count;i++){
try {
placeMap=getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}
this is the screen shot my my log cat:
The problem is somewhere in here:
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results"); // !!! this line here !!!
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
getJSONArray("results"); returns null and that's causing problems later (NullPointerException).
What you should do:
Check your JSON for syntax errors.
Place a breakpoint at the getJSONArray() line and take a look at jsonData and jsonObject if everything is, as it should be.
The array you want to retrieve is probably not valid or not in the jsonData at all.
i would start by validating if the jsonArray is null before running the entire method. or:
if (jsonArray != null)
count=jsonArray.length();
else count = 0;
then debug to find out why you are calling that method with a null object.

Error while displaying json data in android look for error

Display error org.json.JSONException and org.json.typemismatch and org.json.getJSONObject after third log.d("Lee", "working").
This is the code for converting json data to properly formated list view for android.
public class FlowerJSONParser {
public static List<Flower> parserFeed(String content)
{
try
{
Log.d("Lee", "working");
JSONArray ar = new JSONArray(content);
Log.d("Lee", "working");
List<Flower> flowerList = new ArrayList<>();
for(int i=0; i< ar.length(); i++)
{
Log.d("Lee", "working");
JSONObject obj = ar.getJSONObject(i);
Log.d("Lee", "working");
Flower flower = new Flower();
Log.d("Lee", "working");
flower.setId(obj.getString("id"));
flower.setNotes(obj.getString("notes"));
flowerList.add(flower);
}
return flowerList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
You're trying to get JSONObject from JSONArray "ar". So, you must make sure all elements in the array are JSONObject. If not, there must be an exception during convert element to JSONObject.
Please be aware that the element in JSONArray can be any primary type (int/long/boolean...), wrapper class(Integer/Long/Boolean...), String, JSONObject and even another JSONArray.
So, you must confirm the type of element before ar.getJSONObject(i).
Another usage is:
Replace ar.getJSONObject(i) by ar.optJSONObject(i).
In this way, if the element is not a JSONObject, you will get a null instead of an exception.

how to read a json file by hashMap in java

I have a very simple question. I want to read a json file by hashMap in java.
For example I have a json file like this:
{
"list": [
{
"ID" : "#12354667",
"value" : "data1."
}
{
"ID" : "#12345789",
"value" : "data2"
}
And whenever I call the id it returns the value. I have written this but I do not know how to read the file. Any help?
Thanks,
private JsonReader() throws IOException {
//readfile?
this.messages = new HashMap<String, String>();
}
public String getValue(final String ID)
{
if (this.messages.containsKey(ID))
{
return this.messages.get(value);
}
return "";
}
You can use JSONParser and FileReader to read your file into your Application. I'm not quite sure if this is what you searched for, but you can try it. You only have to give your ID to this method.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\yourFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray list= (JSONArray) jsonObject.get("list");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String id= (String) jsonObject.get("ID");
if(id.equals(hereYourFinalString ID)){
String value = (String) jsonObject.get("value");
System.out.println(value);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}

Add Json file contents to JsonObject in Java

I have a Json file E:\\jsondemo.json in disk. I want to create JSONObject in Java and add the contents of the json file to JSONObject. How it is possible?
JSONObject jsonObject = new JSONObject();
After creating this objec, what should i do to read the file and put values in jsonObject
Thanks.
You can transform a file in a String using a function proposed in this question:
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
After getting the string, you can transform it to a JSONObject with the following code:
String json = readFile("E:\\jsondemo.json");
JSONObject jo = null;
try {
jo = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In the above example, I used this library, very simple to learn. You can add values to your JSON object in this way:
jo.put("one", 1);
jo.put("two", 2);
jo.put("three", 3);
You can also create JSONArray objects, and add it to your JSONObject:
JSONArray ja = new JSONArray();
ja.put("1");
ja.put("2");
ja.put("3");
jo.put("myArray", ja);

jsonobject don't support index 0

I have this code in an android app, it take an array where each element is a string that contain the format of jsonObject, but i want to take the value of each object, so use it.The problem is the JsonObject don't take the index 0, so it stared in 1, and i never see the value 1 for the first object.
for(int i=0;i<a.length;i++){
try {
JSONObject jsonn = new JSONObject(a[i]);
g=jsonn.getString(TAG_ID);
builder.append("\n"+i+"."+"id swicht: "+"\n"+g+"\n");
}
} catch (JSONException e) {//e.printStackTrace();}
Based on your comments, the code should be:
jsonStr = jsonStr.substring(1, jsonStr.length() - 1); // (remove the "[" and "]")
String[] a = jsonStr.split(",");
for(int i=0;i<a.length;i++){
try {
JSONObject jsonn = new JSONObject(a[i]);
g = jsonn.getString(TAG_ID);
builder.append("\n"+i+"."+"id swicht: "+"\n"+g+"\n");
} catch (JSONException e) {//e.printStackTrace();}
}
If you don't do the first line, the first and last elem in array will be misformat and cannot be convert JSONObject -- "[{"dpid":"00:00:00:00:00:00:00:0c"}" is not a well format for JSONObject.