I have Json like this..
I used Gson
[
{
"quantity": 12.0,
"product_gid": 15
},
{
"quantity": 6.0,
"product_gid": 18
}
]
I used Json.put
{
"ACTION": "Insert",
"soheader_gid": 0,
"emp_gid": 59,
"custid": 120
}
Now I need to customize the data as
{
"parms": {
"emp_gid": 59,
"soheader_gid": 0,
"custid": "120",
"ACTION": "Insert",
"data": {
"sodetails": [
{
"quantity": 12.0,
"product_gid": 15
},
{
"quantity": 6.0,
"product_gid": 18
}
]
}
}
}
Even this is simple in Python or .net, I am confused how to do in Java Android.
Hi you can try below code to construct your json,
String message;
JSONObject json = new JSONObject();
JSONObject json1 = new JSONObject();
JSONObject json2 = new JSONObject();
JSONObject json3 = new JSONObject();
JSONObject json4 = new JSONObject();
JSONArray jsonArray=new JSONArray();
json1.put("emp_gid", 59);
json1.put("soheader_gid", 0);
json1.put("custid", 120);
json1.put("ACTION", "Insert");
json1.put("data", json2);
json.put("parms", json1);
json3.put("quantity", 12.0);
json3.put("product_gid", 15);
json4.put("quantity", 6.0);
json4.put("product_gid", 18);
jsonArray.put(json3);
jsonArray.put(json4);
json2.put("sodetails", jsonArray);
message = json.toString();
#NOTE: above code is just a process to convert your two json in single one.
We done it by
JSONObject Full_Json = new JSONObject();
JSONObject params_Json = new JSONObject();
params_Json.put(Constant.emp_gid, Integer.parseInt(UserDetails.getUser_id()) );
params_Json.put(Constant.soheader_gid, 0);
params_Json.put(Constant.customer_gid, cust_gid);
params_Json.put(Constant.Action, "Insert");
params_Json.put(Constant.Data, new JSONObject().put(Constant.sodetails, soDetails));
Full_Json.put(Constant.params, params_Json);
soDetails is a Json array
Related
How can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));
I trying to create the code which generates the JSON data which should look like this
{
"Main": [
{
"prim": "Hello ",
"secon": [
{
"ads": "A Message"
}
]
}
]
}
The code I am trying with is generating like below
{
"Main": [
{
"prim": "Hello"
},
{
"secon": [
{
"ads": "A Message"
}
]
}
]
}
Code:
JSONObject prim = new JSONObject();
prim.put("prim", Hello");
JSONObject ads = new JSONObject();
ads.put("ads", "A Message");
JSONArray seconArray = new JSONArray();
seconArray.put(ads);
JSONObject secon = new JSONObject();
secon.put("secon", seconArray);
JSONArray Main = new JSONArray();
Main.put(prim);
Main.put(secon);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Main", Main);
JSONArray topJson = new JSONArray();
topJson.put(jsonObj);
System.out.println(topJson.get(0).toString());
How to remove the unnecessary brackets and create the intended Json data?
Instead of:
secon.put("secon", seconArray);
Try:
prim.put("secon", seconArray);
And remove:
Main.put(secon);
I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
I would have parsed this to get "text" this way, and everything would be ok;
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
And setting
rootobj.get("usethis").getAsJsonArray();
to
rootobj.get("").getAsJsonArray();
just gives me an error. How would I be able to parse the second json?
JsonElement is just a superclass of JsonArray and JsonObject.
JsonArray items = root.getAsJsonArray();
should do what you want.
i have a json-file called "user.json". Now i want to add a new user. I know how to get the content of the file and put it in a String, but i dont know how to add new content correctly. "jsonString" is the content of "user.json"
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
The output is:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
But it should be:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
Does somebody know how to do it right?
I looked it up but all the examples are not working for me, because when i try
JSONObject object = new JSONObject(jsonString);
or
JSONArray array = new JSONArray(jsonString);
i always get "the constructor ist undefined".
Edit:
content of user.json
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:
I solved the problem
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
it seems you are adding fields to your jsonObject, and what you want to do it basically adding the new object to the inner json array (in this case field is called "user"
try this:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
you can use fromObject() method:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);
I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.
You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}
Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}