I am trying below code....
public String listToJsonString(String keyName, List<StyleAttribute> attrs) {
JSONObject json = new JSONObject();
json.accumulate(keyName, attrs);
return json.toString();
}
But when i am checking json variable it contains empty values something like below
{"myKey":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
And when i am checking attrs variables it contains 22 element Data.What i am doing Wrong here? I am just converting my List to Json Object and save to Database.
I am using
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
You can use below code
public String listToJsonString(List<StyleAttribute> attrs) {
JSONObject jObject = new JSONObject();
try {
JSONArray jArray = new JSONArray();
for (MyClass myObject: attrs) {
JSONObject styleJSON = new JSONObject();
styleJSON.put("name",myObject.getName());
styleJSON.put("rollNumber", myObject.getRollNumber());
jArray.add(styleJSON);
}
jObject.put("keyName", jArray);
} catch (Exception jse) {
}
return jObject.toString();
}
It will resolve your issue.
Not sure on this one but maybe the objects in your List are serializable.
Also, what library do you use to manage JSON?
EDIT :
So json-lib it is!
I found this in the json-lib FAQ :
Json-lib creates empty JSONObjects from my bean class, help me!
Json-lib uses the JavaBeans convention to inspect your beans and create
JSONObjects. If the properties of your beans do not adhere to
the convention, the resulting JSONObject will be empty or half empty.
You must provide a read/write method pair for each property.
Here's the wikipedia page talking about the JavaBeans conventions:
http://en.wikipedia.org/wiki/JavaBeans#JavaBean_conventions
Hope this will help you!
Related
Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github
After some researchs, I didn't have found any solutions to this problem:
when I create a JSONObject (org.json) from a file, it return "empty":false. Why does it return this and how can I fix it?
Java:
JSONObject config = new JSONObject(Files.readAllLines(Paths.get("config/maj.json")));
JSON:
{"FyloZ":"0"}
Files.readAllLines is working return the right value.
Thanks!
Files.readAllLines() returns List<String>, not a String.
So actually you are using the following constructor (accepting a single Object parameter):
https://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.Object-
Construct a JSONObject from an Object using bean getters
The only getter-style method of a List is isEmpty(), so you get that 'empty: false' thing.
Try the following:
String json = new String(Files.readAllBytes(Paths.get("config/maj.json")), "utf-8");
JSONObject config = new JSONObject(json);
Here we read JSON as bytes, convert them to a string (assuming it's in utf-8) and then create a JSONObject from it.
I thanks for taking a look.
I'm working on a problem where I need to be able to get a Json into memory and be able to "navigate" around the keys.
I am able to use the Json.createParser() method and use the FileReader in the args to get the file in my system. My problem is that from there I don't yet have a way to take the JsonParser object to JsonObject to read values from.
I am using the package javax.json.
I want to be able to navigate around the Json data I have easily with JsonObject and JsonArray but using the JsonParser object.
Thanks for your time.
Okay I figured it out.
Here is what the json looks like:
{
"name": "Changed name",
"Items":
[
{"item1": "the_fist_item"},
{"item2": "the_second_item"},
{"item3": "the_second_item"}
]
}
then inside the java...
import java.io.FileReader;
import javax.json.*;
public class JsonTester
{
public static void main(String[] args)
{
try
{
JsonReader json_file = Json.createReader(new FileReader("***the directory to the json file***"));
JsonObject json_object = json_file.readObject();
String the_second_item = json_object.getJsonArray("Items").getJsonObject(1).get("item2").toString();
System.out.println(the_second_item);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The navigating part I was trying to accomplish is on the_second_item. Which is all the get() methods to go deeper into the Json file to get the specific value I wanted.
Thanks to David Ehrmann for his help.
I am working with an exiting API that expects a "Metadata" field as part of its json payload. That "Metadata" field is a json object that is completely free-form. Currently, I need to read this data provided from another source, do some enrichment, then pass it on. I am struggling with how to define this "Metadata" object so that it can be any valid json object. OR, if that field was not provided, an empty json object.
I attempted to use org.json.JSONObject like so.
//meta is the json string read from the db
JSONObject jsonobject = new JSONObject(meta);
message.Metadata = jsonobject;
However, jackson, not unexpectedly, threw a serialization error:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered...
This is a critical requirement that I'm guessing I am missing some relatively obvious solution to. Any help would be greatly appreciated.
UPDATED FIX
As suggested by #shmosel I just switched the json object to a com.fasterxml.jackson.databind.JsonNode and all works beautifully.
// working code (rough of course)
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = null;
try {
rootNode = mapper.readTree(meta);
} catch (IOException e) {
e.printStackTrace();
}
message.Metadata = rootNode;
I have always used XML for returning data from my servlets and i have decided to have a go with JSON.Simple.
I currently have;
public JSONObject loadDetails() throws IOException {
JSONArray list = new JSONArray();
list.add(new Car("car1",3,4,3,2,4,5));
list.add(new Car("car2",3,4,3,2,4,5));
StringWriter out = new StringWriter();
list.writeJSONString(out);
System.out.println(out.toString());
return null;
}
I am trying to store some car details, however when i try and print i just get the object names rather than the correct JSON value. My car class implements JSONStreamAware eg;
public void writeJSONString (Writer out) throws IOException{
LinkedHashMap obj = new LinkedHashMap();
obj.put("carname", carname);
obj.put("engine", engine);
JSONValue.writeJSONString(obj, out);
}
Have i missed something here?
I am sorry, I know that this is not what you are explicitly asking for but I will definitely recommend using Gson for json parsing. You jsut specify several annotations and everything is magically serialized / deserialized. Read about gson here. Again sorry that this is not exact answer of the question, but still I hope it will help you get started in json.