Converting string array into json - java

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.

Related

Java JSONObject getJsonArray Blank String

I have some JSON that is returned as follows:
[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]
I am trying to split these into two arrays and get the strings out as follows:
jsonResultsObject = new JSONObject(result);
jsonArray = jsonResultsObject.getJSONArray("");
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
However the code never goes into the loop, as the array is not getting populated from the JSONObject?
your result is JSONArray not JSONObject. That's why you must convert it to array not to object.
use
jsonResultsArray = new JSONArray(result);
instead of
jsonResultsObject = new JSONObject(result);
and the full code will be
jsonResultsArray = new JSONArray(result);
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonResultsArray.length()){
JSONObject JO = jsonResultsArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
#BigJimmyJones
The fact of that the code does not enter the loop is just because your JSONArray does not have a key named "" but it contains JSONObjects instead. Objects and arrays in JSON have different annotations. See: JSON Reference Website
So your code should be :
jsonResultsObject = new JSONObject(result);
String onArrive, onReady, onFinished;
for (int i=0;i<jsonArray.length();i++){
JSONObject JO = jsonArray.getJSONObject(i);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
}
And also ensure that your code is inside a try - catch block to catch JSONException

create a json data object in java

Can someone provide me java code to create a json object as shown below
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
I have tried something like
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
I am getting the result like below even when I am looping
{"main":["one","two","three","four","five"]}
like a single object. But I am expecting the result like
{"main":[
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"],
["one","two","three","four","five"]
]}
Many thanks in advance.
try this code to create json
Gson gson = new Gson();
JsonArray array = new JsonArray();
JsonArray child = new JsonArray();
child.add(new JsonPrimitive("One"));
child.add(new JsonPrimitive("two"));
child.add(new JsonPrimitive("three"));
child.add(new JsonPrimitive("four"));
child.add(new JsonPrimitive("five"));
for(int i=0;i<5;i++)
array.add(child);
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);
System.out.println(jsonObject);
Assuming you're using Gson, this isn't the way it was designed to be used. Though this way is supported, it is not suggested, as you could use any json library to do this (SimpleJson).
Instead, Gson is able to directly serialize java objects we are familiar with, so you should represent your json object as a java object. JsonObject maps to a Map. JsonArray maps to List or an array. JsonPrimitives are mapped to their respective java primitive types (boolean, double, string, null)
// generate the object
Map<List<List<String>>> object = new HashMap<>();
List<List<String>> main = new ArrayList<>();
List<String> counts = Arrays.asList("one", "two", "three", "four", "five");
for (int i = 0; i < 5; i++) {
main.add(counts);
}
object.put("main", main);
// serialize it
String json = new Gson().toJson(object);
// deserializing it requires a typetoken or separate class representing the map object.
Map<List<List<String>>> desObj = new Gson().fromJson(json, new TypeToken<Map<List<List<String>>>>(){}.getType());
It appears "main" contains an array of arrays, so all you would have to do is add your array five times to another new array (e.g. call it mainArray) and then add mainArray to your jsonObject:
Create a new empty array: mainArray
Add array five times to mainArray
Add mainArray to jsonObject
You can try to convert the string representing your json data to JsonObject:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonQuestion {
public static void main(String[] args) {
String myJSON = "{\"main\":[\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"],\n"
+ " [\"one\",\"two\",\"three\",\"four\",\"five\"]\n"
+ "]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(myJSON);
System.out.println("jsonObject: " + jsonObject.toString());
}
}
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("One"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
array.add(new JsonPrimitive("four"));
array.add(new JsonPrimitive("five"));
JsonObject jsonObject = new JsonObject();
JsonArray marray = new JsonArray();
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
marray.add(array);
jsonObject.add("main", marray);
You can use below method to make json :
private void createJsonData(){
final String[] units = {"One","Two","Three","Four",
"Five"};
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
for (int j = 0; j < 5 ; j++) {
jsonArray1.put(units[j])
}
jsonArray.put(jsonArray);
jsonObject.put("main",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use this method
public static void newjson() {
JSONObject json =new JSONObject();
List<List<String>> listoflist = new ArrayList<List<String>>();
List<String> list=new ArrayList<String>();
list.add("one");
list.add("one");
list.add("one");
listoflist.add(list);
listoflist.add(list);
try {
json.put("main",listoflist);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
}

Read JSON in java servlet

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

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();
}

Creating JSONObjects in android

I need to form a JSON object like this.
{
"GroupID": 24536,
"Section": [1,2,3,4,5]
}
Here is what i have tried, but the section array is not getting properly formed when i look at my object structure.
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
Object.put("Section", section);
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
Integer[] section = {1,2,3,4,5};
Object.put("Section", new JSONArray(Arrays.asList(section)));
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
JSONArray arr = new JSONArray();
arr.put(section);
Object.put("Section", arr);
Or create a Collection and set it as the value:
Collection c = Arrays.asList(section);
Object.put("Section", c);
You need to make use of JSONArray for inserting set of values that represent an array, in this case int array.
String strJson = null;
try{
int[] section = {1,2,3,4,5};
JSONObject jo = new JSONObject();
jo.put("GroupId", 24536);
JSONArray ja = new JSONArray();
for(int i : section)
ja.put(i);
jo.put("Section", ja);
strJson = jo.toString();
}
catch (Exception e) {
e.printStackTrace();
}
Now you've got json string inside strJson.

Categories

Resources