I was looking this for creating JSON and the output is
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
But i want an array of 10 times like this
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.5",
"platform": "Win 95+",
},
And this is the way I tried
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class TestJson {
public static void main(String[] args) {
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
try {
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
but this only prints 1 json
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
}
you can do this:
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<10;i++){
JSONObject obj = new JSONObject();
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//if you are using JSON.simple do this
array.add(obj);
//and if you use json-jena
array.put(obj);
}
jsonObject.put("MyArray" , array);
System.out.print(jsonObject);
In the following code
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
you are creating a single JSONObject and overwriting its values 10 times.
Why are you working with a JSONObject when you want a JSON array?
Create a JSONArray and add 10 JSONObject objects to it.
Related
I create json file with the folloing code:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSON file created: "+jsonObject);
}
}
OUTPUT:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}
How can I add content of java map to the this json output as a new node sothat I have at the end the following output:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1",
"data": {
"a": "Test1",
"b": "Test2"
}
}
You just need to add another object of type JsonObject and it will do that
//...
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("data", new JSONObject(data));
//...
And that will return the output what you want
In case you need add more fields without a object a good practice its do the next:
JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);
This return:
{
"id":"1",
"data":{
"field1": "some cool",
"field2": "not cool"
}
}
how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]
Response string is like this:
{
"images": [
{
"transaction": {
"status": "success",
"topLeftX": 325,
"topLeftY": 451,
"gallery_name": "Ironman",
"subject_id": "Tony",
"confidence": 0.99414,
"height": 630,
"width": 630,
"face_id": 1,
"quality": 1.75477
},
"candidates": [
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644861022"
},
{
"subject_id": "Tony",
"confidence": 0.99414,
"enrollment_timestamp": "1487644876280"
}
]
}
]
}
I tried this code but not working..
JSONArray arr = new JSONArray(response);
JSONObject jObj = arr.getJSONObject(0);
String status = jObj.getString("status");
String message = jObj.getString("subject_id");
Use json simple lib
JSONObject json = new JSONObject(yourString);
JSONArray images = json.getJSONArray("images");
and you can loop throw this array
for (int i = 0; i < images.length(); i++) {
JSONObject o = images.getJSONObject(i);
....
}
You can use GSON to parse JSON Strings. If you just want the first object of the images array you can use this code:
JsonParser jsonParser = new JsonParser();
JsonObject obj = jsonParser.parse(responseString).getAsJsonObject();
JsonArray images = obj.getAsJsonArray("images");
String subjectId = images.get(0).getAsJsonObject().get("transaction")
.getAsJsonObject().get("subject_id").getAsString();
You can create pojo class for response
Also you can use GSON library for get response string.
use this
#Override
protected void onPostExecute(String result) {
JSONObject jsonobj;
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
if (result.equals("failure")) {
Toast.makeText(context, "Check your Username or Password", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString()); JSONArray array = jsonobj.getJSONArray("images");for (int i = 0; i < array.length(); i++) {
JSONArray transaction = array.getJSONObject(i).getJSONArray("transaction");for (int i = 0; i < array.length(); i++)
String status = transaction.getJSONObject(i).getString("status");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
dialog.dismiss();
Toast.makeText(context, "Check net connection", Toast.LENGTH_LONG).show();
}
}
You tried
JSONArray arr = new JSONArray(response);
but you should
JSONObject arr = new JSONObject(response);
Because your main json is json object, not JSONArray
I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}
Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!
I have this simple class:
class element{
public int id;
public String name;
}
and this JSON file:
[
{
"id": 1,
"name": "water"
},
{
"id": 2,
"name": "fire"
}
...
]
How do I load this JSON in List? Can somebody suggest to me a good JSON library for this? Can I use Jar in android ?
You can also use built in org.json library in android, for your case you can use:
List<Element> elements = new LinkedList<Element>();
JSONArray arr = new JSONArray(jsonString);
JSONObject tempObj;
Element tempEl;
for(int i = 0; i < arr.length(); i++){
tempObj = arr.getJSONObject(i);
tempEl = new Element();
tempEl.id = tempObj.getInt("id");
tempEl.name = tempObj.getString("name");
elements.add(tempEl);
}
And you will get a list of elements.
Try Jackson; it can handle this and much more.
Its very easy to this. Here is the complete code
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public List<element> generateList()
{
String jsonString = "[{\"id\": 1,\"name\": \"water\"},{\"id\": 2,\"name\": \"fire\"}]";
JSONArray json = null;
List<element> mElementList = new ArrayList<element>();
try {
json = new JSONArray(jsonString);
} catch (JSONException je) {
Log.e("TAG", "Json Exception" + je.getMessage() );
return;
}
JSONObject jsonObject = null;
element ele = null;
for (int i = 0; i < json.length(); i++) {
try {
jsonObject = json.getJSONObject(i);
ele = new element();
if(jsonObject.has("id"))
{
ele.id = jsonObject.getString("id")
}
if(jsonObject.has("name"))
{
ele.name = jsonObject.getString("name")
}
mElementList.add(ele);
} catch (JSONException jee) {
Log.e("TAG", "" + jee.getMessage());
}
}
return mElementList;
}