0

here is my pojo

public class Data{
 List<Object> objects;
 String owneruid;
}

if the out put is pure json like this

{"object":[{"p1":100,"p2":"name","p3":"sfa0","p4":300}],"owneruid":"owneruid"}

then iam able to convert with no worries but here is my output

{  
  "object":"[{\"p1\":32,\"p3\":470,\"p3\":\"213\",\"p4\":\"name\"}]",
  "owneruid":"6697729776330393738"
}

im converting a json string to string because to store in my db as it does not accept json so when i query returns like above so every time i need to fetch the value and convert it to json object and put it in list and display. can you suggest me a better approach.

And when i try to convert a list of custom classes to json using GSON

ArrayList<Object> list=new ArrayList<>();
    Object object=new Object();
    object.setP1(3);
    object.setP2(4);
    list.add(object);
    
    Gson gson=new Gson();
    String json = gson.toJson(list);

 Required:
{"object":[{"p1":100,"p2":"name","p2":"sfa0","p4":300}],"owneruid":"owneruid"}

buts it ends like this

{"object":"[{\"p1\":313,\"p2\":470,\"p3\":\"1521739327417\",\"p4\":\"name\"}]","owneruid":"6697729776330393738"}
3

2 Answers 2

1

You have to use any json frameworks. E.g. Jackson or Gson. As alternative you could do smth. like this. Just evaluate JavaScript.

public static void main(String... args) throws ScriptException {
    ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
    Object obj = js.eval("[{\"width\":313,\"height\":470,\"mediauid\":\"1521739327417\",\"mediatype\":\"image\"}]");
    // res is either List<Object> or Map<String, Object> 
    Object res = convertIntoJavaObject(obj);
}

private static Object convertIntoJavaObject(Object obj) {
    if (!(obj instanceof ScriptObjectMirror))
        return obj;

    ScriptObjectMirror mirror = (ScriptObjectMirror)obj;

    if (mirror.isArray())
        return mirror.entrySet().stream()
                     .map(entry -> convertIntoJavaObject(entry.getValue()))
                     .collect(Collectors.toList());

    Map<String, Object> map = new HashMap<>();
    mirror.entrySet().forEach((key, value) -> map.put(key, convertIntoJavaObject(value)));

    return map;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the below code snippet as it seems fit for your case. ObjectMapper can be found with Jackson framework. inputJson is the JSON string you have mentioned.

ObjectMapper mapper = new ObjectMapper();
Object mediaMetaDataObj = mapper.readValue( inputJson, Object.class );

Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.