how to store a Json object using spark java framework - java

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

Related

Parsing JsonObjectRequest

I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");

storing an JSON array in java code array in android

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

Convert string to JSON and get value

I have this string:
{"markers":[{"tag":"1","dep":"2"}]}
How to convert it to JSON and get value tag and dep?
you need JSONObject to do this
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tag, dep;
JSONArray jArray = response.getJSONArray("markers");
JSONObject msg = jArray.getJSONObject(0);
tag = msg.getString("tag");
dep = msg.getString("dep");
}
}
try
{
JSONObject object = new JSONObject(json_str);
JSONArray array= object.getJSONArray("markers");
for(int i=0;i<array.length();i++)
{
JSONObject obj= array.getJSONObject(i);
String tag= obj.getString("tag");
int dep= obj.getInt("dep");
}
}catch(JSONException e){
}
Hope this helps.
it's good habbit to serialize the json to pojo object ..
here you can use Gson (a google library to serialize/deserialize json to pojo object)
Assuming you are using Android-Studio IDE for android development
Step 1 : add this gson dependency on build.gradle file of module scope
compile 'com.google.code.gson:gson:2.4'
Step 2: create model for json
{"markers":[{"tag":"1","dep":"2"}]}
Markers.java
public class Markers {
/**
* tag : 1
* dep : 2
*/
private List<MarkersEntity> markers;
public void setMarkers(List<MarkersEntity> markers) {
this.markers = markers;
}
public List<MarkersEntity> getMarkers() {
return markers;
}
public static class MarkersEntity {
private String tag;
private String dep;
public void setTag(String tag) {
this.tag = tag;
}
public void setDep(String dep) {
this.dep = dep;
}
public String getTag() {
return tag;
}
public String getDep() {
return dep;
}
}
}
Step 3: serialise json string to pojo object using gson
Gson gson = new Gson();
Markers markers = gson.fromJson(<jsonstring>.toString(), Markers.class);
Step 4: iterate the markers.getMarkersEntity() to get values of tag & dep
for(MarkersEntity data:markers.getMarkersEntity())
{
String tag = data.getTag();
String dep = data.getDep();
Log.d("JSON to Object", tag +"-"+dep);
}
You can use Ion Library for this and parse it as follows:
Ion.with(MainActivity.this).load("url").asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject arg1) {
// TODO Auto-generated method stub
if(arg0==null)
{
arg1.get("markers").getAsJsonArray();
JsonObject Jobj=arg1.getAsJsonObject();
String tag=Jobj.get("tag").getAsString();
String dep=Jobj.get("dep").getAsString();
}
}
});
Here, you may find your solution. Try it.
try {
//jsonString : {"markers": [{"tag":"1","dep":"2"}]}
JSONObject mainObject = new JSONObject(jsonString);
JSONArray uniArray = mainObject.getJSONArray("markers");
JSONObject subObject = uniArray.getJSONObject(0);
String tag = subObject.getString("tag");
String dep = subObject.getString("dep");
} catch (JSONException e) {
e.printStackTrace();
}

Faster way to parse a JSON String in android

I'm using this method to parse a JSON string, but it is too slow... is there a better way to do it?
Thanks
synchronized private void parseCategories(String response){
try{
JSONArray categoriesJSONArray = new JSONArray (response);
// looping through All Contacts
for(int i = 0; i < categoriesJSONArray.length(); i++){
JSONObject currentCategory = categoriesJSONArray.getJSONObject(i);
String label="";
String categoryId="";
// Storing each json item in variable
if(currentCategory.has("label"))
label = currentCategory.getString("label");
if(currentCategory.has("id"))
categoryId = currentCategory.getString("id");
if(
label!=null &&
categoryId!=null
)
{
Category toAdd = new Category(categoryId, label);
categories.add(toAdd);
}
}
//Alphabetic order
Collections.sort(
categories,
new Comparator<Feed>() {
public int compare(Feed lhs, Feed rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
}
);
Intent intent = new Intent("CategoriesLoaded");
LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
}catch (JSONException e) {
e.printStackTrace();
}
}
Here's try following code to start with. You would need Gson library for it.
Gson gson=new Gson();
MyBean myBean=gson.fromJson(response);
Note: Here MyBean class contains the fields present in you json string for e.g. id, along with getter and setters. Rest of all is handled by Gson.
Here's a quick demo.
import com.google.gson.annotations.SerializedName;
public class Box {
#SerializedName("id")
private String categoryId;
// getter and setter
}
Say you JSON looks as following:
{"id":"A12"}
You can parse it as follows:
class Parse{
public void parseJson(String response){
Gson gson=new Gson();
Box box=gson.fromJson(response,Box.class);
System.out.println(box.getCategoryId());
}
}
Output :
A12
For more on Gson visit here
Use GSON library. You can convert your object to json string like the following example:
MyClass MyObject;
Gson gson = new Gson();
String strJson = gson.toJson(MyObject);

Jersey - Json to java string

I am new to JSON web service. I want to convert below simple JSON structure to Java String. Though I have referred many sites, still it adds more confusion to me. I am using GSON for parsing but alwasy getting
"java.lang.IllegalStateException: This is not a JSON Array."
Please assist me to resolve the issue.
JSON DATA : {"data1":"100","data2":"hello"}
JAVA CODE :
private void getPostMessage(String msg) {
try {
EmployeeBean emp;
String json;
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/JSON_EMP_Serv/rest/server/post/");
ClientResponse response = webResource.type("application/json").post(ClientResponse.class,msg);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("\n============get POST Message Response============");
System.out.println(output);
/******* JSON PARSER **********/
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(output).getAsJsonArray();
ArrayList<EmployeeBean> lcs = new ArrayList<EmployeeBean>();
for(JsonElement obj : Jarray )
{
emp = gson.fromJson(obj,EmployeeBean.class);
lcs.add(emp);
}
int length=lcs.size();
System.out.println("ARRAY LENGTH"+length);
for(int i=0;i<length;i++)
{
System.out.println(lcs.get(i)+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
EMPLOYEEBEAN CLASS :
package com.pats.client.bean;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class EmployeeBean {
private String data1= null;
private String data2 = null;
public EmployeeBean(String data1,String data2)
{
this.data1=data1;
this.data2=data2;
}
public String getData1()
{ return data1; }
public String getData2()
{ return data2; }
public void setData1(String data1)
{
this.data1=data1;
}
public void setData2(String data2)
{
this.data2=data2;
}
#Override
public String toString() {
//return "[data1=" + data1 + ", data2=" + data2 + "]";
return " DATA-1 : " + this.data1 + "DATA-2 : " + this.data2;
}
}
The point is, clearly, that your data is not a JSON array.
{"data1":"100","data2":"hello"}
It is, instead, a JSON object, but you are trying to parse it and get a JsonArray. You could change this and use getAsJsonObject() instead, but from your code I think it's your starting data that is wrong. I guess you should have an array of employees, so the correct data should probably be something like:
[{"data1":"100","data2":"hello"}]

Categories