How to get Jsonobject from list in java? - java

I have two jsonobject which is in list. If I make new jsonobject and trying to get list in that it is giving me null.
Code is here below-
private int isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
JSONObject obj = new JSONObject(profile.get(i));
log.info("--------------" + obj.toString()); //it is giving me an empty object but list contains two objects {"size":"M","id":11} and {"size":8,"id":19}
}
}

I tried this it worked
private void isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
if(profile.get(i)!=null) {
JSONObject obj = new JSONObject(profile.get(i).toString());
System.out.print("keys----------" + obj.toString());
}
}
}
public void processList() {
try {
JSONObject objA= new JSONObject("{\n" +
" \"size\": \"M\",\n" +
" \"id\": 11\n" +
" }");
JSONObject objB=new JSONObject("{\n" +
" \"size\": 8,\n" +
" \"id\": 19\n" +
" }");
List<JSONObject> list=new ArrayList<>();
list.add(objA);
list.add(objB);
isExisting("",list,"");
} catch (JSONException e) {
e.printStackTrace();
}
}

I have tried this simple logic and it is working fine-
private int isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
JSONObject obj = (JSONObject) profile.get(i);
log.info("--------------" + obj.toString());
}
}

Related

JSONArray for array of String giving A JSONObject text must begin with '{' at 1 [character 2 line 1]

I am reading a JSON string and trying to get value for a given key.
code to get value from JSON
private static void getKey(JSONObject jsonObject, String key) {
boolean exist = jsonObject.has(key);
Iterator<?> keys;
String nextKey;
if(!exist) {
keys = jsonObject.keys();
while (keys.hasNext()) {
nextKey = (String) keys.next();
System.out.println("Key is :: " + nextKey);
try {
if(jsonObject.get(nextKey) instanceof JSONObject) {
if(!exist) {
getKey(jsonObject.getJSONObject(nextKey), key);
}
} else if(jsonObject.get(nextKey) instanceof JSONArray) {
JSONArray jsonArray = jsonObject.getJSONArray(nextKey);
for(int i = 0; i < jsonArray.length(); i++) {
String arrayValue = jsonArray.get(i).toString();
JSONObject innerJSONObject = new JSONObject(arrayValue.trim());
if(!exist) {
getKey(innerJSONObject, key);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
parseJSONObject(jsonObject, key);
}
}
I am trying to parse this JSON String
String data = "[{\n" +
"\t\"siteName\": \"tvt-ieee\",\n" +
"\t\"personId\": \"43038888\",\n" +
"\t\"editorId\": \"43038888-tvt-ieee\",\n" +
"\t\"emails\": [{\n" +
"\t\t\"emailAddress\": \"02superjh#gmail.com\"\n" +
"\t}],\n" +
"\t\"keywords\": [\"H.1.2 User/Machine Systems\",\"I.2 Artificial Intelligence\"],\n" +
"}]";
JSONArray jsonObject = new JSONArray(data);
getKey(jsonObject.getJSONObject(0), "keywords");
but when I am trying to get value for key "keywords" it is throwing an error like
A JSONObject text must begin with '{' at 1 [character 2 line 1]
please help me how can I solve this issue?
Thank you in advance

com.fasterxml.jackson.databind.JsonMappingException while sending Json

I am not able to send JsonObject through rest controller:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: JsonObject; nested exception is com.fasterxml.jackson.databind.JsonMappingException: JsonObject (through reference chain: com.google.gson.JsonObject[0]->com.google.gson.JsonObject["asString"])
private String str = "{ \"document\": [\n" +
" {\n" +
" \"file\": \"PayrollFAQ.pdf\",\n" +
" \"type\": \"pdf\",\n" +
" \"title\": \" FAQ for Payroll\",\n" +
" \"rating\": 4.5,\n" +
" \"confidence\": 0.9\n" +
" }\n" +
" ]}";
#RequestMapping(value = "/posttest", method = RequestMethod.POST, produces="application/json" )
public #ResponseBody ResponseEntity posttest(#RequestBody Information inputReq) {
JsonParser jsonParser = new JsonParser();
List testArray = new ArrayList();
JsonObject objectFromString = jsonParser.parse(str).getAsJsonObject();
testArray.add(HrBotUtilities.getArrayJSON(objectFromString, "document"));
System.out.println("testString : "+testArray.get(0));
return ResponseEntity.status(HttpStatus.OK).body(testArray.get(0));
}
// HrBotUtilities.getArrayJSON Method
public static JsonObject[] getArrayJSON(JsonObject docObj, String name) {
JsonObject[] list = null;
if (docObj.has(name)) {
JsonArray json;
json = docObj.getAsJsonArray(name);
int lenFeatures = json.size();
list = new JsonObject[lenFeatures];
for (int j = 0; j < lenFeatures; j++) {
JsonObject f = json.get(j).getAsJsonObject();
list[j] = f;
}
}
return list;
}
Please help me

How to get Json data

I have a json array like this
{
"success":"true",
"crops": {
"Brinjal":[---varieties of brinjal---],
"apple":[---varieties of apple---],
.................
.................
}
}
So i have got the complete crops using.....
JSONObject jsonObject;
jsonObject.getString("crops")
but i actually need to create two arrays like
String[] crops = {"Brinjal","apple"};
String[] varities = {"---Brinjal Varities---","---apple varities---"};
how can I generate these two arrays
if i generate "crops" then i can generate other array....
so how can i generate the "crops"...
You should do:
JSONObject obj = new JSONObject(jsonStringResp);
JSONObject cropsObj = obj.getJSONObject("crops");
JSONArray arr1 = subObject.getJSONArray("Brinjal");
Then you iterate over the JSON array and create the String array.
Hope it helps you.
public static void main(String[]args){
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<Object> apple = new ArrayList<Object>();
List<Object> Brinjal = new ArrayList<Object>();
apple.add("---varieties of apple---");
Brinjal.add("---varieties of brinjal---");
Map<String,Object> mapF = new HashMap<String,Object>();
Map<String,Object> mapS = new HashMap<String,Object>();
mapS.put("Brinjal", Brinjal);
mapS.put("apple", apple);
mapF.put("success", "true");
mapF.put("crops",mapS );
JSONObject obj = new JSONObject().fromObject(mapF);
System.out.println(obj);
JSONObject objF = obj.getJSONObject("crops");
String[] ListF = {};
String str = objF.keySet().toString();
String strF = str.substring(1, str.length()-1);
ListF = strF.split(", ");
List<Object> lsitF = new ArrayList<Object>();
for(int i = 0;i<ListF.length;i++){
lsitF.add(objF.get(ListF[i]));[enter image description here][1]
}
System.out.println(str);
System.out.println(lsitF.toString());
}
Hope it helps you.
Try this:
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<String> whereCrops = new ArrayList<String>();
List<String> whereVarities = new ArrayList<String>();
String[] crops;
String[] varities;
ArrayList<String> contentKey = new ArrayList<String>();
try {
JSONObject myObject = new JSONObject(joson);
JSONObject jsonCrops = myObject.getJSONObject("crops");
Iterator<String> iter = jsonCrops.keys();
while (iter.hasNext()) {
String key = iter.next();
whereCrops.add(key);
Log.e("inningskey", key);
try {
JSONArray array = jsonCrops.getJSONArray(key);
whereVarities.add(array.toString());
} catch (JSONException e) {
// Something went wrong!
}
}
// here ! you need convert whereCrops to crops
} catch (JSONException e) {
e.printStackTrace();
}
}

Can't decode Json array values?

How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.

How do you parse JSON with a colon in the name? Android/Java

For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;

Categories

Resources