I want to store the json array sent by php code in java array in android. My php code is working perfectly fine but in the app I get name: as the output. I want to display the names in the texview for checking purpose. Also I want to work with the namesby accessing them one by one.
Php code:
echo json_encode(array("result"=>$result));
Java code:
public class Salary {
public static final String DATA_URL1 = "http://********.com/name.php?salary=";
public static final String KEY_name = "name";
public static final String JSON_ARRAY1 = "result";
}
This is a method of my Name.java
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Salary.JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject collegeData = result.getJSONObject(i);
name = collegeData.getString(Salary.KEY_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult1.setText("Name:\t" + name);
}
Use GSON Library
ArrayList<Salary> salaryArrayList = new ArrayList<>();
try {
salaryArrayList = new Gson().fromJson(response, new TypeToken<Salary>() {}.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
Then use salaryArrayList to get values.
Download GSON jar from this link
Related
I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}
I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;
I want to create a model whose structure is as shown below
"SettingsConfiguration":{
loadingOccupancy:[
{
berthId:Number,
laneId:Number,
berthCapacity:Number,
routeNo:String,
speciallyChallengedCapacity:Number
}
],
smsNotification:{
phoneNo:Number,
smsSendingStatus:Boolean
}
}
using spark java ,I am able to do for the simple structure as shown below
package com.models;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.types.ObjectId;
public class Map {
private String id;
private String title;
public Map(BasicDBObject dbObject) {
this.id = ((ObjectId) dbObject.get("_id")).toString();
this.title = dbObject.getString("title");
}
public String getTitle() {
return title;
}
}
But not sure how to construct the class for the above data structure
please help how to construct the class i.e, how to parse and store the above JSON format which is coming from the request body
Steps which you could try >
1.Method to read the request using the paramater of the method HttpServletRequest request eg : protected void doPost(HttpServletRequest request).
2. And try to write a method like this :
protected void doPost(HttpServletRequest request){
String jsonString = IOUtils.toString(request.getInputStream());
try {
jsonObject = new JSONObject(jsonString);
JSONArray entryArray = new JSONArray(jsonObject.get("SettingsConfiguration")
.toString());
JSONObject entryObj = entryArray.getJSONObject(0);
JSONArray loadingOccupancyArray = new JSONArray(entryObj.get("loadingOccupancy")
.toString());
JSONObject loadingOccupancyObject = loadingOccupancyArray.getJSONObject(0);
JSONObject sender = (JSONObject) loadingOccupancyObject.get("berthId");
JSONObject recipient = (JSONObject) loadingOccupancyObject.get("laneId");
JSONObject message = (JSONObject) loadingOccupancyObject.get("laneId");
System.out.println("message = " + message.get("text"));
System.out.println("sender = " + sender.get("id"));
System.out.println("recipient = " + recipient.get("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Use Jackson [Java JSON parser (http://jackson.codehaus.org)] library. Please refer Parsing JSON File Java for more information
i have a problem how to cast JSONObject or String to integer..
I send data once as a JSONObject
#GET
#Produces(MediaType.APPLICATION_JSON)
public JSONObject sayJSONHello() {
JSONArray numbers = new JSONArray();
numbers.put(1);
numbers.put(2);
numbers.put(3);
numbers.put(4);
JSONObject result = new JSONObject();
try {
result.put("numbers", numbers);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
And one as a String
#Path("/test")
public class Hello {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String sayJSONHello() {
String myString =null;
try
{
myString = new JSONObject().put("data", "1 2 4").toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
return myString;
}
Then, i have problem how to receive this data as a Int.
I tried like this (Client):
Syste m.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).get(String.class));
System.out.println(service.path("rest").path("test").accept(MediaType.APPLICATION_JSON).get(String.class));
String k = service.path("rest").path("test").accept(MediaType.APPLICATION_JSON).get(String.class);
// ERROR int temp = Integer.parseInt(k);
Could anyone advise how to deal with it ?
Your variable k is storing the whole JSON. You would need to parse the JSON object first and then pull out the specific integer (I assume in the array?) that you want.
Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}