Add Json file contents to JsonObject in Java - json

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);

Related

Xml To Json Conversion with same value needed in Json Without Exponential Form

I convert Xml Data to Json Data and my input in xml file or text file is:-
//**xml input:- <data>34123456.00</data>**
String jsonFileName = "src\\main\\resources\\Light.json";
try {
File xmlFile = new File("src\\main\\resources\\output.txt");
InputStream inputStream = new FileInputStream(xmlFile);
StringBuilder builder = new StringBuilder();
int ptr;
while ((ptr = inputStream.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
JSONObject jsonObj = XML.toJSONObject(xml);
System.out.print(jsonObj);
FileWriter fileWriter =
new FileWriter(jsonFileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
bufferedWriter.write(jsonObj.toString(PRETTY_FACTOR));
bufferedWriter.close();
} catch (IOException ex) {
System.out.println(
"Error writing to file '"
+ jsonFileName + "'");
} catch (Exception e) {
e.printStackTrace();
} /* json output is :- {"data":3.4123456E7}
I want Output as :- {"data":34123456.00} */
but i dont want exponential form in json format i want complete number so how i do this in Java ?
JSONObject jsonObj = XML.toJSONObject(xml,true);
write above line instead of
JSONObject jsonObj = XML.toJSONObject(xml);
this solves my problem.

Java save json byte array image to particular location

I have one application that posts json data like below
{
"image": "data:image/png;base64,eAvQPaQEJCABCUjg/wNeEta73J3yXwAAAABJRU5ErkJggg==................"
}
It posts image(png or jpg) base64 byte array in the "image" key.
I want to save that image under the name "datetime.png" into my specified location.
For this I am using the code below:
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/getImage")
public Response GetImage(String json) {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
String currentTime = sdf.format(dt);
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
String imageCode=innerJsonObj.getString("image");
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
FileOutputStream fos = new FileOutputStream("D:\\image\\" + currentTime + ".png");
try {
fos.write(imageBytes);
} finally {
fos.close();
}
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But it gives me the following Error
java.io.FileNotFoundException: D:\image\2016-07-15 17:04:34.png (The
filename, directory name, or volume label syntax is incorrect)

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.

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.

how to create a Json String in blackberry

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();
}