java 如何在JAVA的action类中创建一个JSON对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/944285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:30:12  来源:igfitidea点击:

how to create a JSON object in action class of JAVA

javajsonxstream

提问by Jugal

I want to create a JSON object. I have tried the following

我想创建一个 JSON 对象。我已经尝试了以下

myString=new JSONObject().put("JSON", sampleClass).toString();

but mystring gives me {"SampleClass@170f98"}.

但 mystring 给了我 {"SampleClass@170f98"}。

I also tried the following

我也尝试了以下

 XStream xsStream=new XStream(new JsonHierarchicalStreamDriver());
 SampleClass sampleClass=new SampleClass(userset.getId(),userset.getUsername());
 myString=xsStream.toXML(sampleClass);

It works but when i use getJSON in javascript to get myString it does not work.

它有效,但是当我在 javascript 中使用 getJSON 来获取 myString 时它不起作用。

回答by Mauli

try

尝试

String myString = new JSONObject().put("JSON", new JSONObject(sampleClass)).toString();

in my instance it looks like this:

在我的例子中它看起来像这样:

import org.json.JSONObject;
import org.junit.Test;

public class JsonTest
{
    public static class SampleClass
    {
        private String id;

        private String userName;

        public SampleClass ( String id, String name )
        {
            this.id = id;
            this.userName = name;
        }

        public String getUserName ()
        {
            return userName;
        }

        public void setUserName ( String userName )
        {
            this.userName = userName;
        }

        public String getId ()
        {
            return id;
        }

        public void setId ( String id )
        {
            this.id = id;
        }
    }

    @Test
    public void testSampleClass () throws Exception
    {
        SampleClass sampleClass = new SampleClass ( "myId", "MyName" );
        System.out.println ( new JSONObject ( sampleClass ).toString () );
    }
}

the result looks like this:

结果如下所示:

{"userName":"MyName","id":"myId"}

回答by JohnK

Look into GSON, a Java Library for converting Objects to JSON by Google. [GSON Library][1]

查看 GSON,这是一个由 Google 将对象转换为 JSON 的 Java 库。[GSON 库][1]

From the Google Code site:

从谷歌代码站点:

http://code.google.com/p/google-gson/

http://code.google.com/p/google-gson/

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • 提供简单的 toJson() 和 fromJson() 方法将 Java 对象转换为 JSON,反之亦然
  • 允许预先存在的不可修改对象与 JSON 相互转换

回答by Kees de Kooter

You should try:

你应该试试:

XStream xsStream=new XStream(new JettisonMappedXmlDriver());