String converted JSON Object is not proper while using JSONArray.put(JSONObject) - java

String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";
System.out.println("The JSON string is"+dummyStr);
IS GIVING THE FOLLOWING OUTPUT:
The JSON string is[{"Emp_Id":"1254","Emp_Name":"abcd"},{"Emp_Id":"1234","Emp_Name":"efgh"}]
****But when i try to put into an arraylist it is displaying as ****
tmpJsonArrayList.put(dummyStr)
System.out.println("The JSON string List is"+tmpJsonArrayList);
The JSON string List is["[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]"]

You may use JsonParser to convert the string to json array:
String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";
JsonParser parser = new JsonParser();
// parse the string as JsonArray
JsonArray tmpJsonArrayList = (JsonArray) parser.parse(dummyStr);
System.out.println("The JSON string List is"+tmpJsonArrayList);

String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(dummyStr);
JsonArray tmpJsonArrayList = jsonElement.getAsJsonArray();
System.out.println("The JSON string List is"+tmpJsonArrayList);
This is how we can parse json string in java. You will need to add com.google.gson library to compile this code.

Related

java gson json object array to string array

I am a beginner with JAVA and are using the gson library to convert a JSON string something like this:
String json = "{\"Report Title\": \"Simple Embedded Report Example with Parameters\",\"Col Headers BG Color\": \"yellow\",\"Customer Names\":[\"American Souvenirs Inc\",\"Toys4GrownUps.com\",\"giftsbymail.co.uk\",\"BG&E Collectables\",\"Classic Gift Ideas, Inc\"]}";
Gson gson = new Gson();
jsonObject (Map) = gson.fromJson(json, Object.class);
But the problem is I need the "Customer Names" array to be returned as a string array and not an object array.
Can gson do this or would it have to be converted afterwards by somehow detecting the type (array) and then looping over each element converting it to a string array and replacing the object array ?
The added problem is that the JSON field names are not fixed, and there may be multiple arrays contained in the JSON string and all of them need converting.
you can use jsonarray to get specific field
you can find json api JSON
add json text into file or you can use buffer to pass to parameter
String json = "{\"customer_names\" : [...]}";
then
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("Customer Names");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
or you can use GSON something like this
public class JsonPojo {
private String[] customer_names;
public String[] getCustomerNames(){ return this.customer_names;}
}
public class App{
public static main(String[] args) {
Gson gson = new Gson();
JsonPojo thing = gson.fromJson(json, JsonPojo.class);
if (thing.getCustomerNames()!= null)
{
// do what you want
}
}
}

Can we convert a string to JSON Array using the json-simple-1.1.1.jar library?

I want to convert a string into a JSON Array using the json-simple-1.1.1.jar library and came up with the following code,
import org.json.simple.*;
public class RESTclient {
public static void main(String[] args) {
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
JSONObject jsonObject = new JSONObject(output);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
System.out.println(jsonArray);
}
}
I want the output to be a JSON Array. What am I doing wrong here?
What am I doing wrong here?
You're trying to convert a String that contains a JSON array into a JSONObject
JSONObject jsonObject = new JSONObject(output);
Your content represents a JSON array so parse it as such
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(output);
Note that other libraries, like Gson and Jackson, have much better abstractions for JSON arrays and objects (JsonArray, ArrayNode). Consider using those instead.

Json Object Array Write in Java line by line

I have a Array with some value
when i store that array i got result like this
[{"id":56678,"Name":"Rehman Agarwal"},{"id":66849,"Name":"Rasul Guha"}]
means in a single line.
but I just want to get output like
[{"id":56678,"Name":"Rehman Agarwal"},
{"id":66849,"Name":"Rasul Guha"}]
new line after JSON object ..
How to do it ?
EDIT : i use JSONObject && JSONArray for create json Object and array respectively
Using gson library you can pretty print your json strings like below -
public static String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
}
And call it like below -
public void testPrettyPrint() {
String compactJson = "{\"playerID\":1234,\"name\":\"Test\",\"itemList\":[{\"itemID\":1,\"name\":\"Axe\",\"atk\":12,\"def\":0},{\"itemID\":2,\"name\":\"Sword\",\"atk\":5,\"def\":5},{\"itemID\":3,\"name\":\"Shield\",\"atk\":0,\"def\":10}]}";
String prettyJson = toPrettyFormat(compactJson);
System.out.println("Compact:\n" + compactJson);
System.out.println("Pretty:\n" + prettyJson);
}

SimpleJson: String to JSONArray

I get the following JSON:
[
{
"user_id": "someValue"
}
]
It's saved inside a String.
I would like to convert it to a JSONObject which fails (as the constructor assumes a JSON to start with {). As this doesn't seem to be possible I'd like to convert it to a JSONArray. How can I do that with SimpleJson?
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
For your task you could use code as bellow:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says
JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
for (Object user : userdataArray) {
JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
String User_Id= (String)jsonrow.get("user_Id"); \\ Each User_Id will be displayed.
} else{
System.out.println("Empty Array....");
}
It works for me.
String jsonString = "[{\"user_id\": \"someValue\"}]";
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
try {
jsonArray = (JSONArray) parser.parse(js);
} catch (ParseException e) {
e.printStackTrace();
}

Extract Fields from a Json String in Java

I am trying to extract the ids from each company_id from the following Json String
String test = ["{\"company_id\":4100,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":4045,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":2979,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}"]
I am very new to working with Json. This is what I have so far:
JSONObject jsonObject = new JSONObject(test);
JSONObject newJSON = jsonObject.getJSONObject("company_id");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
I am stuck here because I honestly do not know how would I extract the company_id.
Thank you for your time and patience.
String test = ["{\"company_id\":4100,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":4045,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":2979,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}"]
JSONParser parser = new JSONParser();
Object obj = parser.parse(test);
JSONArray array = (JSONArray)obj;
System.out.println(array.get("company_id"));
I think there is a object array. I think you can get you answer using following way.
for(int i=0;i<array.length();i++){
String company_id=array.getJSONObject(i).getString("company_id");
}

Categories