How to structure Multiple object and array of JSON in java android - java

This is JSON file. I want make java can produce like this json. Just ignore the value, What i want is the structure of the json.
{
"Car": [
{
"CarId": 123,
"Status": "Ok"
},
{
"CarId": 124,
"Status": "ok"
}
],
"Motor": [
{
"MotorId": 3,
"DriverId": 174
},
{
"MotorId": 3,
"DriverId": 174
}
],
"Bus": [
{
"BusId": 8,
"Status": 3
},
{
"BusId": 9,
"Status": 2
}
]
}
This is my java code.
JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
try
{
motorObject.put("Motor",motorArray);
busObject.put("Bus",busArray);
carArray.put(MotorObject);
carArray.put(stepObject);
carObject.put("Car",dataArray);
} catch (JSONException e)
{
e.printStackTrace();
}
The output is :
{
"Car": [
{
"Motor": [
{
"MotorId": 0,
"DriverId": 0
}
]
},
{
"Bus": [
{
"BusId": 0,
"Status": 0
}
]
}
]
}
For value, it's okay, just ignore the value, but what i want how can i get structure like the json file.

Use this code and Enjoy :)
private void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray carArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("CarId", "123");
jsonObject.put("Status", "Ok");
carArr.put(jsonObject);
}
rootObject.put("Car", carArr);
JSONArray motorArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("MotorId", "123");
jsonObject.put("Status", "Ok");
motorArr.put(jsonObject);
}
rootObject.put("Motor", motorArr);
JSONArray busArr = new JSONArray();
for (int i = 0; i < 2 ; i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("BusId", "123");
jsonObject.put("Status", "Ok");
busArr.put(jsonObject);
}
rootObject.put("Bus", busArr);
Log.e("JsonObject", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

JSONObject motorObject = new JSONObject();
JSONObject busObject = new JSONObject();
JSONObject carObject = new JSONObject();
JSONObject wholeObject =new JSONObject();
JSONArray motorArray = new JSONArray();
JSONArray busArray = new JSONArray();
JSONArray carArray = new JSONArray();
motorArray.put(motorTracks.getJSONObject());
busArray.put(buss.getJSONObject());
carArray.put(car.getJSONObject());
try
{
wholeObject.put("Motor",motorArray);
wholeObject.put("Bus",busArray);
wholeObject.put("Car",carArray);
System.out.println(wholeObject);
}
catch (JSONException e)
{
e.printStackTrace();
}

Related

JSON Error: I don't know what type of json file i have. Object or Array? "A JSONArray text must start with '[' at character 1"

This is my JSON file
{
"PartDetails": {
"MyPricing": [{
"BreakQuantity": 200,
"UnitPrice": 0.3787,
"TotalPrice": 75.74
}, {
"BreakQuantity": 600,
"UnitPrice": 0.2932,
"TotalPrice": 175.92
}, {
"BreakQuantity": 1000,
"UnitPrice": 0.2525,
"TotalPrice": 252.5
}, {
"BreakQuantity": 2600,
"UnitPrice": 0.25,
"TotalPrice": 650
}]
}
This is part of my java code. I am trying to pull out MyPricing. I am very new to JSON. Some help would be nice. I don't quite know the syntax that well yet. I have been watching some videos to this point to no avail.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/Public/Documents/JSON/JSONFile.json"));
// String jsonString="";
JSONObject jsonObject = new JSONObject(obj.toString()).getJSONObject("PartDetails");
System.out.println(jsonObject);
JSONArray jsonArray = new JSONArray("MyPricing");
for (int i = 0; i < jsonArray .length(); i++) {
JSONObject _jObj = jsonArray.getJSONObject(i);
JSONObject _jObjTarget = _jObj.getJSONObject("target");
String _indicator_name = _jObjTarget.getString("indicator_name");
System.out.println("Indicator Name : " + _indicator_name);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray("MyPricing"); -creates a new json array out of the string "MyPricing" (the string is not an array so this fails)
try:
JSONArray jsonArray = jsonObject.getJSONArray("MyPricing"); - this takes the array that lies inside your object

my json parser for jsonarry just get the first element

i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")

How to extract an array of JSON inside JSON array

{
"hits": [
{
"name": "Google",
"results": [
{
"count": 27495
}
]
},
{
"name": "Yahoo",
"results": [
{
"count": 17707
}
]
}
}
i'am able to read the name and results from the above json by the below code, but unable to print the count value alone from JSON.
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
}
}
How to extract an array of JSON inside JSON array
Just as you parsed for Outer JSONArray (hits ) . Follow the same for inner ("results") :
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
JSONArray innerarray = (JSONArray) tempJsonObj.get("results");
for(int i=0;i<innerarray.size() ; i++)
{
JSONObject tempJsoninnerObj = (JSONObject) innerarray.get(i);
System.out.println(tempJsoninnerObj.get("count").toString());
}
}
}

Converting array list object to jsonarray

I have arraylist that needs to be converted to json array to post in the server
the format of json should be like this:
{
p:1,
s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4]
}
Let say I have:
List<MyObject> objectList = new ArrayList<MyObject>();
MyObject myObject = new MyObject();
myObject .setA(1);
myObject .setB(2);
myObject .setA(2);
myObject .setB(3);
myObject .setA(3);
myObject .setB(4);
objectList.add(myObject);
My current code is:
for (int i = 0; i < objectList.size(); i++) {
JSONArray ar = new JSONArray();
ar.put("a:"+objectList.get(i).getA());
ar.put("b:"+objectList.get(i).getB());
jOuter.put("s",ar);
}
but this doesnt work, the current return is:
{"p":1,"s":["a:20","b:10.0"]}
Thanks.
Shouldn't it be something like this?
JSONArray ar = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject objects = new JSONObject();
objects.put("a", objectlist.get(i).getA();
objects.put("b", objectlist.get(i).getB();
ar.put(objects);
}
jOuter.put("s",ar);
Your s entry is actually a JsonArray, while your p is just a property. Here I am using Gson but you could easily apply it to whichever library you are using. So you can do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("p", 1);
JsonArray sArr = new JsonArray();
for (int i = 0; i < objectList.size(); i++)
{
JsonObject innerObj = new JsonObject();
innerObj.addProperty("a:"+objectList.get(i).getA());
innerObj.addProperty("b:"+objectList.get(i).getB());
sArr.add(innerObj);
}
jObj.addProperty("s", sArr);
The output is:
{
"p":1,
"s":[{"a":1,"b":2},{"a":3,"b":4}]
}
Your required format is invalid.
I think you are looking for something like this
{
"p": 1,
"s": [
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 3
},
{
"a": 3,
"b": 4
}
]
}
For this code will be like as below
JSONArray jArray = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject job= new JSONObject();
job.put("a",objectList.get(i).getA());
job.put("b",objectList.get(i).getB());
jArray .put(job);
}
try {
jOuter.put("s", jArray );
} catch (JSONException e) {
e.printStackTrace();
}
Please check following code: This will make the proper formatting:
JSONObject jo = new JSONObject();
try {
jo.put("p", "1");
JSONArray jarr = new JSONArray();
for (MyObject listItem : objectList) {
JSONObject inner = new JSONObject();
inner.put("a", listItem.getA());
inner.put("b", listItem.getB());
jarr.put(inner);
}
jo.put("s", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return output like:
{
"p":1,
"s":[{"a":1,"b":2},{"a":2,"b":3},{"a":3,"b":4}]
}
This makes a proper json, which I think you need! Do let me know, if I am wrong somewhere.

How can i print json objects and array values?

In the Result String i have entire data for that i'm parsing ,i need to print Current Conditions inside values.
current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]
This is my json array ,here i need cloudcover ,weatherDescarrays inside values,how can i print those values.
Here what i did is
JSONParser parser = new JSONParser();
Object obj1 = parser.parse(Result);
JSONObject jobj = (JSONObject) obj1;
JSONObject dataResult = (JSONObject) jobj.get("data");
JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
//out.println(current_condition);
for (int i = 0; i < current_condition.size(); i++) {
}
inside for loop how to repeat and print values ,could anybody help me,thanks in advance.
Assuming that you are using org.json, I would iterate over the array as follows:
public static void main(String[] args) {
String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_su‌​nny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
try {
JSONObject jObj = new JSONObject(json);
JSONObject dataResult = jObj.getJSONObject("data");
JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
for(int i = 0; i < jArr.length();i++) {
JSONObject innerObj = jArr.getJSONObject(i);
for(Iterator it = innerObj.keys(); it.hasNext(); ) {
String key = (String)it.next();
System.out.println(key + ":" + innerObj.get(key));
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Are you using json simple?, if yes, then try :
for (JSONObject object : current_condition) {
System.out.println("cloudcover : " + object.get("cloudcover"));
System.out.println("humidity : " + object.get("humidity"));
}

Categories