如何在Java中动态创建JSON?

huangapple go评论73阅读模式
英文:

How to create JSON dynamically in java?

问题

以下是翻译好的内容:

我有一个CustomerEntity其中包含getter和setter示例customerEntity如下所示

customerEntity =
{
  "customerNumber": "1234",
  "firstName": "Test",
  "email": "test@gmail.com",
  "id": "1",
  "middleName": "doe",
  "phone": "11111"
}

我有一个具有getter和setter的JsonProperty的Java类Attributes如下所示

Attributes = 
{
  "name": "string",
  "value": "string"
}

我有一个列表其中将包含来自CustomerEntity的随机元素例如

List<String> stringlist = { "firstName", "phone" }

我已经创建了一个Attributes类型的列表

List<Attributes> Attributeslist = new ArrayList<>();

我想要创建包含stringlist中所有元素的Attributelist例如在这里它将是
```java
Attributeslist = [
{
  "name": "firstName",
  "value": "Test"
},
{
  "name": "phone",
  "value": "11111"
}
]

为此,我编写了以下代码,但是在previewattributes.setValue();中传递什么?因为该值将取决于下面for循环中的mystring。在这个示例中,它将是previewattributes.setValue(customerEntity.getFirstName());和previewattributes.setValue(customerEntity.getPhone());,但我该如何编写代码呢?

for (String mystring : stringlist) {
Attributes previewattributes;
previewattributes = new Attributes();
previewattributes.setName(mystring);
previewattributes.setValue(value在这里将是customerentity的值);
Attributeslist.add(previewattributes);
}

CustomerEntity:
@Entity
@Table(name = "Customer_tbl")
public class CustomerEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rowId;

@Column(name = "customer_number")
private String customerNumber;

public String getCustomerNumber() {
    return customerNumber;
}

public void setCustomerNumber(String customerNumber) {
    this.customerNumber = customerNumber;
}

}


<details>
<summary>英文:</summary>

I have a CustomerEntiy with getter and setter the sample customerEntity is 

customerEntity =
{
"customerNumber": "1234",
"firstName": "Test",
"email": "test@gmail.com",
"id": "1",
"middleName": "doe",
"phone": "11111"
}

I have java class Attributes of JsonProperty with getter and Setters as below

Attributes =
{
"name": "string"
"value": "string"
}


I have a list which will contains random elements from CustomerEntiy for example:

```List&lt;String&gt; stringlist = { &quot;firstName&quot; , &quot;phone&quot;}```

I have created an List of type Attributes

```List&lt;Attributes&gt; Attributeslist = new ArrayList&lt;&gt;();```



I want to create Attributelist of all the elements in stringlist for Example here it would be:

Attributeslist =[
{
"name": "firstName"
"value": "Test"
},
{
"name": "phone"
"value": "11111"
}
]

For this i have written the code as below but what to pass in  ```previewattributes.setValue();``` because that value would depends on what is ```mystring```  in below for loop. In this example it would be ```previewattributes.setValue(customerEntity.getFirstName());``` and ```previewattributes.setValue(customerEntity.getPhone());``` for different iteration but how do i code it??

for (String mystring : stringlist) {
Attributes previewattributes;
previewattributes = new Attributes();
previewattributes.setName(mystring);
previewattributes.setValue(value here would be of customerentity);
Attributeslist.add(previewattributes);
}


CustomerEntity:

@Entity
@Table(name = "Customer_tbl")
public class CustomerEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name = &quot;id&quot;)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rowId;


@Column(name = &quot;customer_number&quot;)
private String customerNumber;

public String getCustomerNumber() {
    return customerNumber;
}

public void setCustomerNumber(String customerNumber) {
    this.customerNumber = customerNumber;
}

}





</details>


# 答案1
**得分**: 1

**你可以在Java中使用反射。还有更简单的方法是将customerEntity存储在HashMap中,并从中提取。**

```java
HashMap<String, String> m = new HashMap<>();
m.put("customerNumber", customerEntity.getCustomerNumber());
m.put("firstName", customerEntity.getFirstName());
m.put("email", customerEntity.getEmail());
m.put("id", customerEntity.getId());
m.put("middleName", customerEntity.getMiddleName());
m.put("phone", customerEntity.getPhone());

在循环内部:

previewattributes.setValue(m.get(attribute));
英文:

You can make use reflection in Java.
Even more simple way is to store the customerEntity in HashMap and fetch from it.

HashMap&lt;String,String&gt; m=new HashMap&lt;&gt;();
m.put(&quot;customerNumber&quot;, customerEntity.getCustomerNumber());
m.put(&quot;firstName&quot;, customerEntity.getFirstName());
m.put(&quot;email&quot;, customerEntity.getEmail());
m.put(&quot;id&quot;, customerEntity.getId());
m.put(&quot;middleName&quot;, customerEntity.getMiddleName());
m.put(&quot;phone&quot;, customerEntity.getPhone());

And inside for loop:

previewattributes.setValue(m.get(attribute));

答案2

得分: 1

这是你要求的代码部分的翻译结果:

如果我理解你的意思正确你有一个Customer Json数组你想要分离一些属性检查下面的代码

public static void main(String[] args) {

    String jsonArray = "[\r\n" +
            "   {\r\n" +
            "      \"customerNumber\":\"1234\",\r\n" +
            "      \"firstName\":\"Test\",\r\n" +
            "      \"email\":\"test@gmail.com\",\r\n" +
            "      \"id\":\"1\",\r\n" +
            "      \"middleName\":\"doe\",\r\n" +
            "      \"phone\":\"11111\"\r\n" +
            "   },\r\n" +
            "   {\r\n" +
            "      \"customerNumber\":\"1235\",\r\n" +
            "      \"firstName\":\"Test2\",\r\n" +
            "      \"email\":\"test2@gmail.com\",\r\n" +
            "      \"id\":\"2\",\r\n" +
            "      \"middleName\":\"doe2\",\r\n" +
            "      \"phone\":\"2222\"\r\n" +
            "   }\r\n" +
            "]";
    
    List<String> requiredKeys = Arrays.asList("firstName", "phone");
    JSONArray array = new JSONArray(jsonArray);
    Iterator iterator = array.iterator();
    
    JSONArray outputArray = new JSONArray(); 
    while(iterator.hasNext()) {
        JSONObject jsonObject = (JSONObject)iterator.next();
        Iterator<String> keys = jsonObject.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            if(requiredKeys.contains(key)) {
                JSONObject attribute = new JSONObject();
                attribute.put("name", key);
                attribute.put("value", jsonObject.get(key));
                outputArray.put(attribute);
            }
        }
    }
    
    System.out.println(outputArray);
}

输出

[
   {
      "name":"firstName",
      "value":"Test"
   },
   {
      "name":"phone",
      "value":"11111"
   },
   {
      "name":"firstName",
      "value":"Test2"
   },
   {
      "name":"phone",
      "value":"2222"
   }
]

请注意,翻译结果中的代码部分已经按照原文的格式保留。

英文:

If I understood u correctly u have an Array of Customer Json in which u want some attribute separated , check below code

public static void main(String[] args)  {
String jsonArray = &quot;[\r\n&quot; + 
&quot;   {\r\n&quot; + 
&quot;      \&quot;customerNumber\&quot;:\&quot;1234\&quot;,\r\n&quot; + 
&quot;      \&quot;firstName\&quot;:\&quot;Test\&quot;,\r\n&quot; + 
&quot;      \&quot;email\&quot;:\&quot;test@gmail.com\&quot;,\r\n&quot; + 
&quot;      \&quot;id\&quot;:\&quot;1\&quot;,\r\n&quot; + 
&quot;      \&quot;middleName\&quot;:\&quot;doe\&quot;,\r\n&quot; + 
&quot;      \&quot;phone\&quot;:\&quot;11111\&quot;\r\n&quot; + 
&quot;   },\r\n&quot; + 
&quot;   {\r\n&quot; + 
&quot;      \&quot;customerNumber\&quot;:\&quot;1235\&quot;,\r\n&quot; + 
&quot;      \&quot;firstName\&quot;:\&quot;Test2\&quot;,\r\n&quot; + 
&quot;      \&quot;email\&quot;:\&quot;test2@gmail.com\&quot;,\r\n&quot; + 
&quot;      \&quot;id\&quot;:\&quot;2\&quot;,\r\n&quot; + 
&quot;      \&quot;middleName\&quot;:\&quot;doe2\&quot;,\r\n&quot; + 
&quot;      \&quot;phone\&quot;:\&quot;2222\&quot;\r\n&quot; + 
&quot;   }\r\n&quot; + 
&quot;]&quot;;
List&lt;String&gt; requiredKeys = Arrays.asList(&quot;firstName&quot; , &quot;phone&quot;);
JSONArray array = new JSONArray(jsonArray);
Iterator iterator = array.iterator();
JSONArray outputArray = new JSONArray(); 
while(iterator.hasNext()) {
JSONObject jsonObject = (JSONObject)iterator.next();
Iterator&lt;String&gt; keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if(requiredKeys.contains(key)) {
JSONObject attribute = new JSONObject();
attribute.put(&quot;name&quot;, key);
attribute.put(&quot;value&quot;, jsonObject.get(key));
outputArray.put(attribute);
}
}
}
System.out.println(outputArray);
}

}

output

[
{
&quot;name&quot;:&quot;firstName&quot;,
&quot;value&quot;:&quot;Test&quot;
},
{
&quot;name&quot;:&quot;phone&quot;,
&quot;value&quot;:&quot;11111&quot;
},
{
&quot;name&quot;:&quot;firstName&quot;,
&quot;value&quot;:&quot;Test2&quot;
},
{
&quot;name&quot;:&quot;phone&quot;,
&quot;value&quot;:&quot;2222&quot;
}
]

huangapple
  • 本文由 发表于 2020年10月16日 16:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64385549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定