I am new to JSON creations . I want to create a JSON object for each element in the for-each loop. My code is like
for(int i=0 ; i<=childclasses.size() ;i++ ){
for (OInstance oinstance:oinstances){
oinstancelist.add(oinstance);
}
}
try {
object.put("subclass",oclass);
object.put("instance", oinstancelist);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("json is " +object);
I want to create a json object for every oinstance . So,How can i do that ?
With Gson, creating a JSON-String is as easy as:
Gson gson = new Gson();
String json = gson.toJson(oinstance);
GSON is good and always faster then JSON.
However for JSON, Get json-simple-1.1.1.jar and add into your classpath and write below logic to create JSON object
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name", "jsonObject");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
You will get output like : {"balance": 1000.21, "num":100, "is_vip":true, "name":"jsonObject"}
However, as you are new to JSON you can visit this also.
Related
I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
I have following JSON:
{
"data":{
"attributes":{
"external-event-url":"http://example.com",
"is-sponsors-enabled":"true",
"is-ticketing-enabled":"true",
"timezone":"UTC",
"name":"${name_variable}",
"ends-at":"2020-01-02T23:59:59.123456+00:00",
"starts-at":"2020-01-01T23:59:59.123456+00:00"
},
"type":"event"
}
}
I have to iterate through json objects and replace the value of variable starts with ${ e.g. ${name_variable}
and new json should be in same format(with replace value of variable mentioned ${})
How do i iterate such complex Json object and replace the values in variables
I've tried below code but not working as expected:
public Map<String, String> mapfillData(String jsonstr) {
Map<String, String> map = new HashMap<String, String>();
try {
JSONObject jsonObject = new JSONObject(jsonstr);
String[] keys = JSONObject.getNames(jsonObject);
for (String key : keys) {
try {
if (jsonObject.get(key).toString().startsWith("${")) {
map.put(key, System.getProperty(jsonObject.get(key).toString()
.replace("${", "").replace("}", "")));
} else {
if(isJSONValid(jsonObject.get(key).toString())){
mapfillData(jsonObject.get(key).toString());
}else{
map.put(key, jsonObject.get(key).toString());
}
}
} catch (Exception e) {
}
}
} catch (JSONException e) {
System.err.printf(jsonstr + " is not valid Json", e);
}
return map;
}
To check whether its a valid JSON Object
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include #Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
Your problem is that while you are trying to recursively process the JSON, at each level of recursion, you're processing a different JSON document and writing data into a different Map.
Your function takes a string and then parses it into a JSONObject. You create a Map to hold some data. The first time through mapfillData, you're only going to find one key, data. Then, assuming that your if logic works correctly (I didn't try to run it), you're going to render the contents of data into another string and recursively call mapfillData.
Now you're in the second call to mapfillData, and you create another Map. This time through you find attributes and call mapfillData a third time. In this third invocation, you find some variables and replace them when writing the values to Map. At the end of the function, you return the Map, but the caller (the second invocation of mapfillData) doesn't do anything with the returned Map, and all your data is lost.
I would:
Parse the JSON once, then recurse through the JSONObject structure. In other words, the recursive function should take JSONObject.
Just replace the JSON elements in-place.
Or, if you want to flatten the elements and collect them into a Map, then instantiate the Map up-front and pass it into the recursive function.
To convert more easily, you can use the Jackson lib to do the hard stuff:
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{
"data":{
"attributes":{
"external-event-url":"http://example.com",
"is-sponsors-enabled":"true",
"is-ticketing-enabled":"true",
"timezone":"UTC",
"name":"${name_variable}",
"ends-at":"2020-01-02T23:59:59.123456+00:00",
"starts-at":"2020-01-01T23:59:59.123456+00:00"
},
"type":"event"
}
}";
// considering JSONObject matches the Json object structure
JSONObject jsonObject = mapper.readValue(jsonString , JSONObject.class);
Then a little bit of reflection to handle any JSON object fields dynamically:
// with parsed JSON to Object in hands
Class<?> clazz = jsonObject.getClass();
for(Field field : clazz.getDeclaredFields()) {
if(!field.getType().getName().equals("String"))
break;
field.setAccessible(true);
String fieldValue = field.getValue().toString();
if(fieldValue.startsWith("${"))
field.set(jsonObject, fieldValue.replace("${", "").replace("}", ""));
else
// desired treatment
}
I have this js.json file
i want to add another block to the file.
the file now ->
[
{
"diff":"Easy",
"qus":"John1"
}
]
how i want it to be ->
[
{
"diff":"Easy",
"qus":"John1"
},
{
"diff":"Avg",
"qus":"John2"
}
]
You can use org.json library as follow:
JSONArray jsonarray = new JSONArray(jsonStr); //from the file
JSONObject jsonobject = new JSONObject(yourNewlyJsonObject);
jsonarray.put(jsonobject);
System.out.println(jsonarray.toString()); // or write it back to the file
you can check this code.
JSONObject obj = new JSONObject({
"diff":"Avg",
"qus":"John2"
});
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json")); // reading the file and creating a json array of it.
a.put(obj); // adding your created object into the array
// writing the JSONObject into a file(info.json)
try {
FileWriter fileWriter = new FileWriter("c:\\exer4-courses.json"); // writing back to the file
fileWriter.write(a.toJSONString());
fileWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}
References:
https://www.javatpoint.com/json-tutorial
http://www.vogella.com/tutorials/JavaIO/article.html
The following code works fine(!), i wnat to moved it into a own function, but i cant return the from json converted Array (last line). What im doing wronng?
public Array jsonToArray(String json) {
JSONObject myjson = null;
try {
myjson = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray the_json_array = null;
try {
the_json_array = myjson.getJSONArray("profiles");
} catch (JSONException e) {
e.printStackTrace();
}
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = null;
try {
another_json_object = the_json_array.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
arrays.add(another_json_object);
}
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
return Array jsons;
}
I think the Problem is the Type, but im completely new in JAVA... Im getting the error: 'Not a statement'. What is the meaning and the Solution?
public JSONObject[] jsonToArray()
As well as
return jsons;
Or, why not return the ArrayList<JSONObject>, why bother with another conversion?
Though, ideally, returning an actual JSONArray object instead of a Java array of JSONObject makes more sense.
Such as
return myjson.getJSONArray("profiles");
Or, one step further, actually parsing out the values of the JSON you want into your own Java classes?
You should do:
return jsons;
And also correct the return type, you have Array there, I don't see that type defined anywhere in your code, and there is no such type in java, you probably wanted JSONObject[], so the first line of the method will be:
public JSONObject[] jsonToArray(String json) {
I have the following json parsing code which works fine when tested as a java application. But on using it with in an android platform and running , returned the following error
"Unexpected token END OF FILE at position 0"
Here is my code
public boolean parseJSON(String content) {
boolean retvalue=false;
String jsonString=null;
JSONParser parser=new JSONParser();
Object obj;
try {
System.out.println("in the parse json");
obj = parser.parse(content);
JSONArray array=(JSONArray)obj;
JSONObject obj2=(JSONObject)array.get(0);
jsonString=(String) obj2.get("user_id");
System.out.println("in the parse json "+jsonString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != jsonString) {
retvalue = true;
}
return retvalue;
}
The input string for the method is the following
[{"user_id":"1","username":"arvind","password":"somu","firstname":"Arvind somu","accountNumber":"1234567","lastname":"","address":"","email":"sample#gmail.com"}]
I have got the value 1 printed, when tried with java, but no idea why this issue is coming with android. Can body suggest what is wrong with the code.The parser I am using is json-simple1.1.1
Use this:
JSONObject obj2;
obj2 = array.optJSONObject(0);
The method optJSONObject returns a JSONObject and you dont have to cast it, where as get() returns an Object. Try this i think this may solve it.