Read JSON in java servlet - java

I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");

your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");

First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java

if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck

Related

Get String value of json array in a json

For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.

AutoSuggest in Android from jsonencoded array of php

I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}
As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);
You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);

JSON Text data reading in Java

I have text file with JSON data in it with following format:
[ {
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894, } ]
I want to read only brand_family, for which I suppose I need a JSON array.
Do I need to define this format using JSON objects first?
I have downloaded org.json lib, and I have following code in which I am reading the text file, but I cannot find out how do I define format and then import all data in [{}...{}] into an array and:
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
JSONObject obj = new JSONObject(br);
String n = obj.getString("version");
//int a = obj.getInt("age");
System.out.println(n);
}
As mentioned in the comments, your JSON is an array, so firstly you should call:
JSONArray array = new JSONArray(br);
Then you can do something with the size or get the first object:
JSONObject first = array.getJSONObject(0);
And finally, having the JSONObject, you can extract and process any field:
System.out.println(first.getString(""));
You can do it simply as below :
JSONParser parser=new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("D://jsontest.txt")));
JSONArray lang= (JSONArray) jsonObject.get("obj");
for(int i=0; i<lang.size(); i++){
JSONObject obj=(JSONObject) lang.get(i);
System.out.println(obj.get("brand_family"));
}
}catch(Exception e){
e.printStackTrace();
}
Change your file to below :
{
"obj": [
{
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "1",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
},
{
"belongs_to_suite": "yes",
"belongs_to_suite_id": "",
"brand_family": "2",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
}
]
}

Parsing JSON array and object in Android

This is what the JSON looks like:
[{
"pmid": "2",
"name": " MANAGEMENT",
"result": "1",
"properties": [
{
"prop_id": "32",
"prop_name": "Bonneville",
"address": "122 Lakeshore",
"city": "Ripley",
"state": "OH",
"zip": "11454",
"lat": "41.123",
"long": "-85.5034"
}
]
}]
I am trying to parse it with the following Java code in Android:
JSONObject jObj = null;
try {
jObj = new JSONObject(jsonStr);
// We get weather info (This is an array)
JSONArray jArr = jObj.getJSONArray("properties");
// We use only the first value
//JSONObject JSONWeather = jArr.getJSONObject(0);
JSONObject c = jArr.getJSONObject(0);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String phone = c.getString(TAG_PHONE);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
I am not getting any results though. How can I successfully parse this JSON? I'm using Android Studio.
Also, if there were multiple pieces to the array, how could we make sure each one of them is printed out?
Your JSON string start with JSONArray.
Here sample code, try it.
JSONArray mJsonArray = new JSONArray(jsonStr);
JSONObject mJsonObject = mJsonArray.getJSONObject(0);
String pmid = mJsonObject.getString("pmid");
String name = mJsonObject.getString("name");
String result = mJsonObject.getString("result");
JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
for (int i = 0; i < mJsonArrayProperty.length(); i++) {
JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(i);
String prop_id = mJsonObjectProperty.getString("prop_id");
String prop_name = mJsonObjectProperty.getString("prop_name");
String address = mJsonObjectProperty.getString("address");
String city = mJsonObjectProperty.getString("city");
String state = mJsonObjectProperty.getString("state");
String zip = mJsonObjectProperty.getString("zip");
String lat = mJsonObjectProperty.getString("lat");
String lon = mJsonObjectProperty.getString("long");
}
Check Android JSON Parsing Tutorial
As in posted json String jsonStr is JSONArray of JSONObeject's instead of JOSNObject of JSONArray.
So convert jsonStr String to JSONArray:
JSONArray jArray = new JSONArray(jsonStr);
JSONObject c = jArray.getJSONObject(0);
// get properties JSONArray from c
JSONArray jArrProperties = c.getJSONArray("properties");
JSONObject jsonObject = jArrProperties.getJSONObject(0);
Here is complete example with resolution.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args)
{
JSONObject jObj = null;
try {
String jsonStr = "[{\"pmid\":\"2\",\"name\":\" MANAGEMENT\",\"result\":\"1\",\"properties\":[{\"prop_id\":\"32\",\"prop_name\":\"Bonneville\",\"address\":\"122 Lakeshore\",\"city\":\"Ripley\",\"state\":\"OH\",\"zip\":\"11454\",\"lat\":\"41.123\",\"long\":\"-85.5034\"}]}]";
jsonStr = jsonStr.substring(1, jsonStr.length()-1);
System.out.println(jsonStr);
jObj = new JSONObject(jsonStr);
System.out.println("pmid="+jObj.get("pmid"));
System.out.println("name="+jObj.get("name"));
System.out.println("result="+jObj.get("result"));
JSONArray jArr = jObj.getJSONArray("properties");
JSONObject c = jArr.getJSONObject(0);
System.out.println("prop_id=="+c.get("prop_id"));
System.out.println("prop_name=="+c.get("prop_name"));
System.out.println("address=="+c.get("address"));
System.out.println("city=="+c.get("city"));
System.out.println("state=="+c.get("state"));
System.out.println("zip=="+c.get("zip"));
System.out.println("lat=="+c.get("lat"));
System.out.println("long=="+c.get("long"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
in this exammple details object contain j son data
JSONObject details = mJSONParser.doInBackground(); //json object
Child_Registration_StaticData deta=new Child_Registration_StaticData();
try
{
deta.UniqueID = details.getString("UniqueID");
deta.Nameofchild= details.getString("Nameofchild");
deta.FatherName= details.getString("FatherName");
deta.DOB= details.getString("DOB");
child_name.setText(deta.Nameofchild);
father_name.setText(deta.FatherName);
dateof_birth.setText(deta.FatherName);
}
Your root object is a JSON array [], not a JSON object {} there. So, you need
jObj = new JSONArray(jsonStr);
jObj = jObj.getJSONObject(0);
The rest of your code will now work fine treating jObj as a JSONObject. The concept here is exactly the same as what you're doing for your properties JSON array.
use this
try {
JSONArray array0 = new JSONArray(Sample);
JSONObject object0 = array0.getJSONObject(0);
JSONArray array1 = object0.getJSONArray("properties");
JSONObject object1 = array1.getJSONObject(0);
String name = object1.getString("prop_name");
} catch (JSONException e) {
e.printStackTrace();
}

Converting string array into json

My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.

Categories

Resources