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.
Related
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.
I want to access a JSON of this structure in firebase
The structure
{
"questions":{
"English":{
"English_2002":[
{
"correct_ans":"A",
"OptionA":"a coder",
"OptionB":"a hacker",
"OptionC":"a writer",
"OptionD":"a programmer",
"Question":"Who build software"
},
{},
{}
],
"English_2003":[],
}
}
}
I want this structure. In the subject structure, other subjects will come after I exhaust 9 years of English.
My confusion is how to logically get each subject since firebase will only accept the root name questions.
Please I may sound dumb, but I have a very long questions thread almost 55000 lines. Because firebase accept one JSON tree.
Sorry i wasn't very clear i was asking from the stack phone app:
I have a question json tag of the structure above; my question is how will i be able to access the object subject like "english":{
// then accessing the first english array "english":[]
//since am now using firebase.
}
initially each array was individual json file, i have to recreate them into one for firebase sake. this is how i was parsing it then.
public class QuestionParser {
Context context;
public QuestionParser(Context c) {
this.context = c;
}
public ArrayList<Question> getJsonFromUrl(String url, String arrayName)
{
ArrayList<Question> arrayofQuestion = new ArrayList<>();
return arrayofQuestion;
}
// Processing question from JSon file in res > raw folder
public ArrayList<Question> parseQuestionJson(int rawJsonFileId, String arrayName) {
ArrayList<Question> questionList = new ArrayList<>();
String jsonstr = null;
try {
InputStream in = context.getResources().openRawResource(rawJsonFileId);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
jsonstr = sb.toString();
Log.d("REEEEADDD" + this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(jsonstr)) {
return null;
}
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray jsonArray = jsonObject.getJSONArray(arrayName);
JSONObject jobject;
for (int i = 0; i < jsonArray.length(); i++) {
// TEST
jobject = jsonArray.getJSONObject(i);
String ans = jobject.getString("correct_answer");
String graphic_name = jobject.getString("question_image");
String optionA = jobject.getString("optiona");
String optionB = jobject.getString("optionb");
String optionC = jobject.getString("optionc");
String optionD = jobject.getString("optiond");
String questionNo = jobject.getString("question_number");
String question = jobject.getString("question");
questionList.add(new Question(questionNo, graphic_name, question, optionA, optionB, optionC, optionD, ans));
Log.d("DDD" + this.toString(), String.valueOf(questionList.get(i)));
}
Log.i("ONE QUESTION", questionList.get(50).getQuestion());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return questionList;
}
}
So how can i parse it from firebase because initially, if a student chooses question and year i passes those value as parameter and use them for parsing. but in firebase now i have access to only root firebase name in the get reference e method
To access for example "correct_ans":"A" you would query your firebase like so:
your.firebase.domain/questions/English/English_2002/0/correct_ans
Notice that each level in the json object is represented by a / and the key you want to access whereas in case of an array you simple add the array index. JSON's simple structure also allows simple REST like access
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.
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);
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();
}